Pagini recente » Cod sursa (job #34216) | Cod sursa (job #2658281) | Cod sursa (job #183227) | Cod sursa (job #2770284) | Cod sursa (job #3234593)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int kN = 1e3;
const int kInf = 1e9;
int n, m;
vector<int> adj[kN + 1];
int par[kN + 1];
int cap[kN + 1][kN + 1], flow[kN + 1][kN + 1];
void minSelf(int &x, int y) {
if(y < x) {
x = y;
}
}
void addEdge(int u, int v, int c) {
cap[u][v] = c;
flow[u][v] = 0;
adj[u].emplace_back(v);
adj[v].emplace_back(u);
}
bool bfs(int s, int d) {
for(int i = 1; i <= n; i++) {
par[i] = 0;
}
queue<int> q;
q.push(s);
par[s] = s;
while(!q.empty()) {
int u = q.front();
q.pop();
if(u == n) {
return true;
}
for(const auto &it: adj[u]) {
if(par[it] || flow[u][it] == cap[u][it]) {
continue;
}
q.push(it);
par[it] = u;
}
}
return par[d];
}
int bottleneck(int s, int d) {
int res = kInf;
for(int p = d; p != s; p = par[p]) {
minSelf(res, cap[par[p]][p] - flow[par[p]][p]);
}
return res;
}
void pushFlow(int s, int d, int f) {
for(int p = d; p != s; p = par[p]) {
flow[p][par[p]] -= f;
flow[par[p]][p] += f;
}
}
int main() {
fin >> n >> m;
for(int i = 1; i <= m; i++) {
int u, v, c;
fin >> u >> v >> c;
addEdge(u, v, c);
}
int f = 0;
while(bfs(1, n)) {
for(const auto &it: adj[n]) {
par[n] = it;
if(flow[it][n] == cap[it][n] || !par[it]) {
continue;
}
int maxFlow = bottleneck(1, n);
if(maxFlow == 0) {
continue;
}
pushFlow(1, n, maxFlow);
f += maxFlow;
}
}
fout << f << '\n';
return 0;
}