Pagini recente » Cod sursa (job #1632650) | Cod sursa (job #649395) | Cod sursa (job #234251) | Cod sursa (job #31461) | Cod sursa (job #3288471)
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
const int N = 10005, INF = 1e9;
int n, m, capacity[1005][1005];
vector<int> parent;
vector<pair<int, int> > g[N];
int bfs(int s, int t) {
fill(parent.begin(), parent.end(), -1);
parent[s] = 0;
queue<pair<int, int>> Q;
Q.push({s, INF});
while (!Q.empty()) {
int cur_node = Q.front().first;
int cur_flow = Q.front().second;
Q.pop();
for (auto &it: g[cur_node]) {
int nxt_node = it.first, edge_flow = it.second;
if (parent[nxt_node] == -1 && capacity[cur_node][nxt_node]) {
parent[nxt_node] = cur_node;
int new_flow = min(cur_flow, capacity[cur_node][nxt_node]);
if (nxt_node == t)
return new_flow;
Q.push({nxt_node, new_flow});
}
}
}
return 0;
}
int max_flow(int s, int t) {
int flow = 0;
int new_flow = bfs(s, t);
while (new_flow) {
flow += new_flow;
/// scad capacitatea
int cur = t;
while (cur != s) {
int prev = parent[cur];
capacity[cur][prev] += new_flow;
capacity[prev][cur] -= new_flow;
cur = prev;
}
new_flow = bfs(s, t);
}
return flow;
}
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
cin >> n >> m;
parent.resize(n + 5);
parent.assign(n + 5, 0);
for (int i = 1; i <= m; i++) {
int u, v, cst;
cin >> u >> v >> cst;
capacity[u][v] = cst;
capacity[v][u] = 0;
g[u].pb({v, cst});
g[v].pb({u, 0});
}
cout << max_flow(1, n);
return 0;
}