Pagini recente » Cod sursa (job #3121783) | Diferente pentru implica-te/arhiva-educationala intre reviziile 157 si 223 | Cod sursa (job #550265) | Cod sursa (job #921678) | Cod sursa (job #2699214)
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int c[1005][1005], flow[1005][1005], t[1005];
int n, m, maxFlow;
queue<int> coada;
vector<int> G[1005], GRev[1005];
bool bfs() {
memset(t, 0, sizeof(t));
t[1] = -1;
coada.push(1);
while(!coada.empty()) {
int node = coada.front();
coada.pop();
for(auto it = G[node].begin(); it != G[node].end(); ++it) {
if(t[*it] == 0 && (c[node][*it] != 0 && flow[node][*it] < c[node][*it])) {
t[*it] = node;
coada.push(*it);
} else if(t[*it] == 0 && (c[*it][node] != 0 && flow[*it][node] > 0)) {
t[*it] = -node;
coada.push(*it);
}
}
}
return (t[n] != 0);
}
int main() {
f >> n >> m;
for(int i = 1; i <= m; ++i) {
int x, y, capacitate;
f >> x >> y >> capacitate;
G[x].push_back(y);
G[y].push_back(x);
c[x][y] = capacitate;
}
while(bfs()) {
for(auto it = G[n].begin(); it != G[n].end(); ++it) {
if(flow[*it][n] < c[*it][n] && t[*it]) {
int u = *it, val = c[*it][n] - flow[*it][n];
while(u != 1) {
if(t[u] < 0) val = min(val, flow[u][-t[u]]), u = -t[u];
else val = min(val, c[t[u]][u] - flow[t[u]][u]), u = t[u];
}
u = *it;
flow[*it][n] += val;
while(u != 1) {
if(t[u] < 0) flow[u][-t[u]]-= val, u = -t[u];
else flow[t[u]][u] += val, u = t[u];
}
maxFlow += val;
}
}
}
g << maxFlow << '\n';
return 0;
}