Pagini recente » Cod sursa (job #1122881) | Cod sursa (job #673503) | Istoria paginii runda/antrenamentoji/clasament | Cod sursa (job #500927) | Cod sursa (job #1988643)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
vector<int> v[1005];
int c[1005][1005], f[1005][1005], n, m, vis[1005], l[1005];
int bfs()
{
queue<int> q;
q.push(1);
vis[1] = 1;
while(!q.empty() && !vis[n]){
int x = q.front();
q.pop();
for (unsigned i = 0; i < v[x].size(); ++i)
if(!vis[v[x][i]]){
if(f[x][v[x][i]] < c[x][v[x][i]]){
vis[v[x][i]] = x;
q.push(v[x][i]);
}else if (f[v[x][i]][x] > 0){
vis[v[x][i]] = -x;
q.push(v[x][i]);
}
}
}
return !vis[n];
}
int abs(int x)
{
return x >= 0 ? x : -x;
}
int main()
{
ifstream fin ("maxflow.in");
ofstream fout ("maxflow.out");
fin >> n >> m;
while(m--){
int x, y, z;
fin >> x >> y >> z;
if(c[x][y] == 0)
v[x].push_back(y);
if(c[y][x] == 0)
v[y].push_back(x);
c[x][y] = z;
}
do{
for (int i = 0; i < 1005; ++i)
vis[i] = 0;
if(bfs())
break;
int lg = 0;
l[0] = n;
int a;
a = 1000000000;
while(l[lg] != 1){
++lg;
l[lg] = abs(vis[l[lg-1]]);
if(vis[l[lg-1]] > 0)
a = min(a, c[l[lg]][l[lg-1]] - f[l[lg]][l[lg-1]]);
else if (vis[l[lg-1]] < 0)
a = min(a, f[l[lg-1]][l[lg]]);
}
for (int i = lg; i; --i)
if(vis[l[i-1]] > 0)
f[l[i]][l[i-1]] += a;
else f[l[i-1]][l[i]] -= a;
}while(1);
int fm = 0;
for (int i = 1; i <= n; ++i)
fm += f[i][n];
fout << fm << "\n";
fin.close();
fout.close();
return 0;
}