Pagini recente » Cod sursa (job #1093156) | Cod sursa (job #1814202) | Cod sursa (job #1025260) | Cod sursa (job #1021431) | Cod sursa (job #3327840)
#include <vector>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <queue>
#include <stack>
using namespace std;
const int NMAX = 1000;
int flux[NMAX + 1][NMAX + 1];
int capacitate[NMAX + 1][NMAX + 1];
int n, m;
bool vis[NMAX + 1];
int p[NMAX + 1];
vector<int> G[NMAX + 1];
int bfs(int s, int d) {
queue<int> q;
for(int i = 0; i <= n; i++) {
vis[i] = 0;
p[i] = 0;
}
q.push(s);
vis[s] = 1;
while(!q.empty()) {
int x = q.front();
q.pop();
for(auto y : G[x]) {
if(!vis[y] && capacitate[x][y] - flux[x][y] >0) {
vis[y] = 1;
p[y] = x;
q.push(y);
}
}
}
if(vis[d] == 0) {
return 0;
}
vector<int> path;
int r = d;
while(r != 0) {
path.push_back(r);
r = p[r];
}
reverse(path.begin(), path.end());
int mn = 1e9;
for(int i = 0; i < path.size() - 1; i++) {
int x = path[i];
int y = path[i + 1];
mn = min(mn, capacitate[x][y] - flux[x][y]);
}
for(int i = 0; i < path.size() - 1; i++) {
int x = path[i];
int y = path[i + 1];
flux[x][y] += mn;
flux[y][x] -= mn;
}
return mn;
}
int main() {
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
cin >> n >> m;
for(int i = 1; i <= m; i++) {
int x, y, c;
cin >> x >> y >> c;
capacitate[x][y] = c;
G[x].push_back(y);
G[y].push_back(x);
}
int sum = 0;
while(true) {
int flux = bfs(1, n);
sum += flux;
if(flux == 0) {
break;
}
}
cout << sum;
}