Pagini recente » Cod sursa (job #594019) | Monitorul de evaluare | Cod sursa (job #3244365) | Cod sursa (job #3282711) | Cod sursa (job #2699155)
#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 && flow[node][*it] < c[node][*it]) {
t[*it] = node;
coada.push(*it);
}
}
for(auto it = GRev[node].begin(); it != GRev[node].end(); ++it) {
if(t[*it] == 0 && flow[node][*it] > 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);
GRev[y].push_back(x);
c[x][y] = capacitate;
}
while(bfs()) {
for(auto it = GRev[n].begin(); it != GRev[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(c[t[u]][u] == 0) val = min(val, flow[t[u]][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(c[t[u]][u] == 0) flow[t[u]][u] -= val;
else flow[t[u]][u] += val;
u = t[u];
}
maxFlow += val;
}
}
}
g << maxFlow << '\n';
return 0;
}