Pagini recente » Cod sursa (job #1892932) | Cod sursa (job #2746588) | Cod sursa (job #2532455) | Cod sursa (job #2760677) | Cod sursa (job #3259933)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 1e3;
int capacitate[NMAX + 1][NMAX + 1], flux[NMAX + 1][NMAX + 1];
vector<int> G[NMAX + 1];
int n, m;
int vis[NMAX + 1], p[NMAX + 1];
int bfs(int s, int d) {
queue<int> q;
q.push(s);
for(int i = 1; i <= n; i++) {
vis[i] = 0;
p[i] = 0;
}
vis[s] = 1;
while(!q.empty()) {
int node = q.front();
q.pop();
for(auto vecin : G[node]) {
if(!vis[vecin]) {
if(capacitate[node][vecin] - flux[node][vecin] > 0) {
q.push(vecin);
vis[vecin] = 1;
p[vecin] = node;
}
}
}
}
if(!vis[d]) {
return -1;
}
int mn = 1e9;
vector<int> path;
while(d != 0) {
path.push_back(d);
if(p[d] != 0) {
mn = min(mn, capacitate[p[d]][d] - flux[p[d]][d]);
}
d = p[d];
}
reverse(path.begin(), path.end());
for(int i = 0; i < path.size() - 1; i++) {
flux[path[i]][path[i + 1]] += mn;
flux[path[i + 1]][path[i]] -= mn;
}
return mn;
}
int main() {
ifstream f("maxflow.in");
ofstream g("maxflow.out");
f >> n >> m;
for(int i = 1; i <= m; i++) {
int x, y, c;
f >> x >> y >> c;
capacitate[x][y] = c;
G[x].push_back(y);
G[y].push_back(x);
}
//cout << bfs(1, n);
int maxFlow = 0;
int cnt = 3;
while(cnt--) {
int flow = bfs(1, n);
//cout << flow << ' ';
if(flow == -1) {
break;
}
maxFlow += flow;
}
g << maxFlow;
return 0;
}