Pagini recente » Cod sursa (job #436523) | Cod sursa (job #2052623) | Cod sursa (job #995618) | Cod sursa (job #632523) | Cod sursa (job #1023499)
#include <climits>
#include <vector>
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
using namespace std;
#define DBG(x) // std::cout << #x << " " << x << endl
const int MAX_N = 1000 + 2;
int prev[MAX_N], mins[MAX_N];
int c[MAX_N][MAX_N];
vector<int> nodes[MAX_N];
bool bfs(int start, int stop) {
vector<int>::iterator it;
queue<int> q;
memset(prev, 0, sizeof(int) * MAX_N);
memset(mins, 0, sizeof(int) * MAX_N);
q.push(start);
mins[start] = INT_MAX;
bool found = false;
while (!q.empty()) {
int node = q.front(); q.pop();
// DBG(node);
if (node == stop) {
found = true;
break;
}
DBG(nodes[node].size());
for (it = nodes[node].begin(); it != nodes[node].end(); it++) {
// DBG("here");
if (c[node][*it] > 0 && prev[*it] == 0) {
prev[*it] = node;
mins[*it] = min(mins[node], c[node][*it]);
q.push(*it);
}
}
}
return found;
}
void print_c() {
/* for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++)
cout << c[i][j] << " ";
cout << endl;
}*/
}
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);
}
int start = 1, stop = n;
bool found_path = true;
int flow = 0;
while (found_path) {
found_path = bfs(start, stop);
if (found_path) {
DBG("Found path ");
// update the residual capacity along the path
int node = stop;
DBG(mins[stop]);
while (node != start) {
DBG(node);
c[prev[node]][node] -= mins[stop];
node = prev[node];
}
flow += mins[stop];
print_c();
}
}
printf("%d\n", flow);
return 0;
}