Pagini recente » Clasament pre-oji2014 | Cod sursa (job #1760389) | Cod sursa (job #2615572) | Cod sursa (job #2225397) | Cod sursa (job #1023504)
#include <climits>
#include <vector>
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
using namespace std;
const int MAX_N = 1000 + 2;
int previous[MAX_N], c[MAX_N][MAX_N], flow[MAX_N][MAX_N];
vector<int> nodes[MAX_N];
bool bfs(int start, int stop) {
vector<int>::iterator it;
queue<int> q;
memset(previous, 0, sizeof(int) * MAX_N);
q.push(start);
previous[start] = -1;
while (!q.empty()) {
int node = q.front(); q.pop();
if (node == stop) continue;
for (it = nodes[node].begin(); it != nodes[node].end(); it++) {
if (c[node][*it] == flow[node][*it] || previous[*it] != 0)
continue;
previous[*it] = node;
q.push(*it);
}
}
return previous[stop] != 0;
}
int main(int argc, char *argv[]) {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
int n, m, x, y, z;
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &x, &y, &z);
c[x][y] += z;
nodes[x].push_back(y);
nodes[y].push_back(x);
}
int start = 1, stop = n;
bool found_path = true;
int max_flow = 0;
while (bfs(start, stop)) {
for (int i = 0; i < (int)nodes[stop].size(); i++) {
int fmin = INT_MAX;
int node = nodes[stop][i];
if (previous[node] == 0 || c[node][stop] == flow[node][stop]) continue;
previous[stop] = node;
node = stop;
while (node != start) {
fmin = min(fmin, c[previous[node]][node] - flow[previous[node]][node]);
node = previous[node];
}
if (fmin == 0) break;
node = stop;
while (node != start) {
flow[previous[node]][node] += fmin;
flow[node][previous[node]] -= fmin;
node = previous[node];
}
max_flow += fmin;
}
}
printf("%d\n", max_flow);
return 0;
}