Pagini recente » Cod sursa (job #636444) | Cod sursa (job #196106) | Rating Szilagyi Ervin (JohnyErvin) | Cod sursa (job #53909) | Cod sursa (job #2967538)
#include <bits/stdc++.h>
//#include "/usr/local/include/bits/stdc++.h"
// ALGORITMUL EDMONDS-KARP O(V * E^2)
using namespace std;
const int MAX = 1e6;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
vector<vector<int>> capacitate;
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] <= 0) continue;
res = getPath(i, targetNode, curLen + 1, min(maxCap, capacitate[startNode][i]));
if (res > 0) break;
}
return res;
}
int maxFlow(int startNode, int endNode) {
int totalFlow = 0;
while (true) {
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() {
fin >> N >> M;
capacitate.resize(N+1,vector<int>(M));
for (int i = 0; i < M; ++i) {
int x, y, z;
fin >> x >> y >> z;
capacitate[x][y]= z;
}
fout << maxFlow(1, N);
// cin >> N >> M;
// capacitate.resize(N+1,vector<int>(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;
}