Pagini recente » Cod sursa (job #96202) | Cod sursa (job #1474826) | Cod sursa (job #477804) | Cod sursa (job #3214567) | Cod sursa (job #2967800)
#include <bits/stdc++.h>
#define INF 2147000000
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int n, m, a, b, c;
vector<vector<int>> capacity;
vector<vector<int>> adjlist;
// Edmonds-Karp
// O(
int maxflow(int s, int t) {
int flow = 0;
vector<int> parent(n+1);
while (true) {
fill(parent.begin(), parent.end(), -1);
queue<int> q;
q.push(s);
parent[s] = -2;
while (!q.empty() && parent[t] == -1) { // Run BFS until the sink is visited or the queue is empty
int u = q.front();
q.pop();
for (int v : adjlist[u]) {
if (parent[v] == -1 && capacity[u][v] > 0) {
parent[v] = u;
q.push(v);
}
}
}
if (parent[t] == -1) break; // If the sink has not been visited, then there is no more augmenting path
int bottleneck = INF;
for (int v = t; v != s; v = parent[v]) {
bottleneck = min(bottleneck, capacity[parent[v]][v]);
}
for (int v = t; v != s; v = parent[v]) { // Starting from the sink, go through the path to the source
capacity[parent[v]][v] -= bottleneck; // Reduce the capacity of the edges in the augmenting path by the bottleneck capacity
capacity[v][parent[v]] += bottleneck; // Increase the capacity of the reverse edges by the bottleneck capacity
}
flow += bottleneck;
}
return flow;
}
int main() {
f >> n >> m;
capacity.resize(n + 1, vector<int>(n + 1, 0));
adjlist.resize(n + 1);
for (int i = 1; i <= m; i++) {
f >> a >> b >> c;
adjlist[a].push_back(b);
capacity[a][b] = c;
}
g << maxflow(1, n);
return 0;
}