Pagini recente » Cod sursa (job #346116) | Cod sursa (job #1737411) | Cod sursa (job #25264) | Cod sursa (job #1779850) | Cod sursa (job #1516282)
#include <fstream>
#include <vector>
#include <bitset>
#include <limits.h>
#include <queue>
#define DIM 351
#define INF INT_MAX
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
int N, M, beginning, ending, x, y, cap, c, minimum, solution;
int capacity[DIM][DIM], flow[DIM][DIM], cost[DIM][DIM];
int T[DIM], D[DIM];
vector<int>L[DIM];
bitset<DIM>V;
queue<int>q;
int bellman_ford()
{
for(int i = 1; i <= N; i ++)
{
D[i] = INF;
V[i] = 0;
}
D[beginning] = 0;
q.push(beginning);
while(!q.empty())
{
int node = q.front();
V[ node ] = 0;
q.pop();
for(int i = 0; i < L[ node ].size(); i ++)
{
int neighbour = L[ node ][i];
if( (D[neighbour] > D[ node ] + cost[ node ][neighbour]) && (flow[ node ][neighbour] < capacity[ node ][neighbour] ) )
{
D[neighbour] = D[ node ] + cost[ node ][neighbour];
T[ neighbour ] = node;
if(V[neighbour] == 0)
{
q.push(neighbour);
V[neighbour] = 1;
}
}
}
}
if(D[ending] != INF)
{
return 1;
}
return 0;
}
int main()
{
fin >> N >> M >> beginning >> ending;
for(int i = 1; i <= M; i ++)
{
fin >> x >> y >> cap >> c;
L[x].push_back(y);
L[y].push_back(x);
capacity[x][y] = cap;
cost[x][y] = c;
cost[y][x] = -c;
}
while(bellman_ford())
{
minimum = INF;
int x = ending;
while(x != beginning)
{
if(minimum > capacity[ T[x] ][x] - flow[ T[x] ][x] )
{
minimum = capacity[ T[x] ][x] - flow[ T[x] ][x];
}
x = T[x];
}
x = ending;
while(x != beginning)
{
solution += minimum * cost[ T[x] ][x];
flow[ T[x] ][x] += minimum;
flow[x][ T[x] ] -= minimum;
x = T[x];
}
}
fout << solution;
return 0;
}