Cod sursa(job #575354)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define inf 0x3f3f3f3f
using namespace std;
const char iname[] = "fmcm.in";
const char oname[] = "fmcm.out";
const int nmax = 380;
ifstream fin(iname);
ofstream fout(oname);
int n, m, s, dest, i, x, y, c, z;
vector<pair <int, int> > Gr[nmax];
int F[nmax][nmax], C[nmax][nmax], T[nmax], rezid, cost, d[nmax];
int bellman_ford()
{
int viz[nmax], t[nmax];
for(i = 1; i <= n; i ++)
{
t[i] = 0;
viz[i] = 0;
d[i] = inf;
}
queue<int> Q;
viz[s] = 1;
d[s] = 0;
Q.push(s);
while(!Q.empty())
{
x = Q.front();
Q.pop();
for(vector<pair <int, int> >::iterator it = Gr[x].begin(); it != Gr[x].end(); ++it)
{
if(F[x][it->first] < C[x][it->first] && d[x] + it->second < d[it->first])
{
d[it->first] = d[x] + it->second;
if(viz[it->first] == 0)
{
viz[it->first] = 1;
Q.push(it->first);
}
T[it->first] = x;
}
}
}
if(d[dest] != inf)
return 1;
return 0;
}
int main()
{
fin >> n >> m >> s >> dest;
for(i = 1; i <= m; i ++)
{
fin >> x >> y >> c >> z;
Gr[x].push_back(make_pair(y , z));
Gr[y].push_back(make_pair(x, -z));
C[x][y] = c;
}
for(i = 1; i <= n; i ++)
d[i] = inf;
while(bellman_ford())
{
rezid = inf;
rezid = C[T[dest]][dest] - F[T[dest]][dest];
for(i = dest; T[i] ; i = T[i])
rezid = min(rezid, C[T[i]][i] - F[T[i]][i]);
for(i = dest; T[i] ; i = T[i])
{
F[T[i]][i] += rezid;
F[i][T[i]] -= rezid;
}
cost += rezid * d[dest];
for(i = 1; i <= n; i ++)
d[i] = inf;
}
fout << cost << "\n";
return 0;
}