Pagini recente » Istoria paginii utilizator/roxana_2222 | Cod sursa (job #2013898) | Profil Alexxxx | Istoria paginii utilizator/dancojocaru2000 | Cod sursa (job #2967514)
//#include <bits/stdc++.h>
#include "/usr/local/include/bits/stdc++.h"
// ALGORITMUL EDMONDS-KARP O(V * E^2)
using namespace std;
#define MAX 10000
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int capacitate[MAX][MAX];
int path[MAX];
bool vizitat[MAX];
int M, N;
int pathLength;
// DFS, BFS, DIJKSTRA
int getPath(int startNode, int targetNode, int curLen, int maxCap) {
path[curLen] = startNode;
if (startNode == targetNode) {
pathLength = curLen + 1;
return maxCap;
}
int res = 0;
vizitat[startNode] = true;
for (int i = 1; i <= N; ++i) {
if (vizitat[i] || capacitate[startNode][i]) continue;
res = getPath(startNode, targetNode, curLen + 1, min(maxCap, capacitate[startNode][i]));
if (res > 0) break;
}
return res;
}
int maxFlow(int startNode, int endNode) {
int totalFlow = 0;
while (1) {
memset(vizitat, false, sizeof (vizitat));
int newFlow = getPath(startNode, endNode, 0, INT_MAX);
if (newFlow <= 0)break; // once there is no paths anymore stop the algo
for (int i = 1; i <= pathLength; ++i) {
int m = path[i - 1];
int n = path[i];
capacitate[m][n] -= newFlow;
capacitate[n][m] += newFlow;
}
totalFlow += newFlow;
}
return totalFlow;
}
//4 5
//1 2 3
//1 3 5
//2 4 6
//3 4 4
//3 2 3
int main() {
cin >> N >> M;
for (int i = 0; i < M; ++i) {
int x, y, z;
cin >> x >> y >> z;
capacitate[x][y] = z;
}
cout << maxFlow(1, N);
return 0;
}