Pagini recente » Cod sursa (job #2177819) | Cod sursa (job #3123013) | Cod sursa (job #687826) | Cod sursa (job #2251709) | Cod sursa (job #2960322)
#include <iostream>
#include <cstdio>
#include <bitset>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
const int MAXN = 1005;
int n, m, x, y, c;
int capacity[MAXN][MAXN];
int flow[MAXN][MAXN];
int father[MAXN];
int source, destination;
bitset<MAXN> explored;
bool bfs() {
for(int i = 1; i <= n; i++) {
father[i] = 0;
}
explored.reset();
explored[source] = 1;
queue<int> q;
q.push(source);
while(!q.empty()) {
int node = q.front();
q.pop();
if (node == destination) {
while(!q.empty()) q.pop();
return 1;
}
for(int i = 1; i <= n; i++) {
if(flow[node][i] < capacity[node][i] && explored[i] == 0) {
explored[i] = 1;
q.push(i);
father[i] = node;
}
}
}
if(explored[destination] == 0)
return 0; // destination can't be reached!
else
return 1; // destination reached!
}
int main() {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++ )
{
scanf("%d%d%d", &x, &y, &c);
capacity[x][y] = c;
}
source = 1;
destination = n;
int max_flow = 0;
while(bfs()) {
int node = destination;
int min_flow = INT_MAX;
// calculate the maximal flow that can be pushed through this path
while(father[node] != 0) {
min_flow = min(min_flow, capacity[father[node]][node] - flow[father[node]][node]);
node = father[node];
}
node = destination;
max_flow += min_flow;
while(father[node] != 0) {
flow[father[node]][node] += min_flow;
flow[node][father[node]] -= min_flow;
node = father[node];
}
}
printf("%d", max_flow);
return 0;
}