Pagini recente » Cod sursa (job #711286) | Cod sursa (job #1125209) | Cod sursa (job #3249915) | Cod sursa (job #539425) | Cod sursa (job #989615)
Cod sursa(job #989615)
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int NMAX = 1003;
#define FILEIN "maxflow.in"
#define FILEOUT "maxflow.out"
vector<int> A[NMAX];
int cap[NMAX][NMAX];
int flow[NMAX][NMAX];
int t[NMAX];
int N, M;
bool mark[NMAX];
bool bfs() {
queue<int> Q;
memset(mark, 0, sizeof(mark));
Q.push(1);
while(!Q.empty()) {
int nod = Q.front(); Q.pop();
if ( nod == N ) continue;
for ( size_t j = 0; j < A[nod].size(); j++) {
int next = A[nod][j];
if (cap[nod][next] == flow[nod][next] || mark[next]) continue;
mark[next] = 1;
Q.push(next);
t[next] = nod;
}
}
return mark[N];
}
int detfmin(int nod) {
int f = 0x3f3f3f3f;
for ( nod = N; nod != 1; nod = t[nod]) {
f = min(f, cap[t[nod]][nod] - flow[t[nod]][nod]);
}
return f;
}
void rmfmin(int nod, int f) {
for ( nod = N; nod != 1; nod = t[nod]) {
flow[t[nod]][nod] += f;
flow[nod][t[nod]] -= f;
}
}
int main() {
freopen(FILEIN, "r", stdin);
freopen(FILEOUT, "w", stdout);
scanf("%d %d", &N, &M);
for ( int i = 1, x, y, z; i <= M; i++ ) {
scanf("%d %d %d", &x, &y, &z);
cap[x][y] = z;
A[x].push_back(y);
A[y].push_back(x);
}
int sol = 0;
while(bfs()) {
for ( int i = 0; i < A[N].size(); i++) {
int nod = A[N][i];
if (flow[nod][N] == cap[nod][N] || !mark[nod]) continue;
t[N] = nod;
int fminim = detfmin(nod);
if (!fminim)
continue;
rmfmin(nod, fminim);
sol += fminim;
}
}
printf("%d\n", sol);
return 0;
}