Pagini recente » Cod sursa (job #1962421) | Cod sursa (job #2157744) | Cod sursa (job #1288198) | Cod sursa (job #633633) | Cod sursa (job #2963540)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int n, m, max_flow;
vector<vector<int>> adjacence_list;
vector <vector <int>> used_cap;
vector <int> root;
bool bfs() {
root.assign(n + 1, 0);
queue <int> q;
q.push(1);
while (!q.empty()) {
int nod = q.front();
q.pop();
if (nod == n) {
return true;
}
for (auto vecin : adjacence_list[nod]) {
int current_used_cap = used_cap[nod][vecin];
if (current_used_cap > 0 && root[vecin] == 0) {
root[vecin] = nod;
q.push(vecin);
}
}
}
return false;
}
int main() {
f >> n >> m;
adjacence_list = vector<vector<int>>(n + 1);
root = vector<int>(n + 1, 0);
used_cap = vector<vector<int>>(n + 1, vector <int>(n + 1, 0));
int x, y, z;
for (int i = 0; i < m; ++i) {
f >> x >> y >> z;
adjacence_list[x].push_back(y);
adjacence_list[y].push_back(x);
used_cap[x][y] = z;
}
// edmonds-karp
while (bfs()) {
for (auto node : adjacence_list[n]) {
if (root[node]) { // daca nodul are parinte dupa trecerea prin bfs
root[n] = node; // il setam ca parintele destinatiei
int current_flow = INT_MAX;
int i = n;
while (i != 1) {
current_flow = min(current_flow, used_cap[root[i]][i]);
i = root[i];
}
i = n;
while (i != 1) {
used_cap[root[i]][i] -= current_flow;
used_cap[i][root[i]] += current_flow;
i = root[i];
}
max_flow += current_flow;
}
}
}
g << max_flow << '\n';
// // b) Min-Cut
// g << "\nMin-cut:\n";
//
// queue <int> q;
// vector <bool> visited(n + 1, false);
//
// visited[1] = true;
// q.push(1);
//
// while (!q.empty()) {
// int nod = q.front();
// q.pop();
//
// if (nod == n) {
// break;
// }
//
// for (auto vecin: adjacence_list[nod]) {
// int current_used_cap = used_cap[nod][vecin];
//
// if (current_used_cap > 0 && !visited[vecin]) {
// q.push(vecin);
// visited[vecin] = true;
// }
// }
// }
//
// for (int i = 1; i <= n; i++) {
// for (auto vecin: adjacence_list[i]) {
// if (visited[i] && !visited[vecin]) { // daca putem ajunge in i din sursa, dar in vecinul lui nu
// g << i << " " << vecin << '\n';
// }
// }
// }
f.close();
g.close();
return 0;
}