Pagini recente » Cod sursa (job #174817) | Cod sursa (job #1207149) | Cod sursa (job #2754265) | Cod sursa (job #1469151) | Cod sursa (job #1023502)
#include <climits>
#include <vector>
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
using namespace std;
#define DBG(x) //std::cerr << #x << " " << x << endl
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];
void print_c() {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++)
cout << c[i][j] << " ";
cout << endl;
}
}
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;
// DBG("HERE");
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);
}
DBG("HERE");
int start = 1, stop = n;
bool found_path = true;
int max_flow = 0;
while (found_path) {
// DBG("HERE");
found_path = bfs(start, stop);
if (found_path) {
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;
DBG("HERE");
previous[stop] = node;
node = stop;
while (node != start) {
fmin = min(fmin, c[previous[node]][node] - flow[previous[node]][node]);
node = previous[node];
}
DBG(fmin);
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;
}