Pagini recente » Cod sursa (job #1542603) | Cod sursa (job #2413296) | Cod sursa (job #3251658) | Cod sursa (job #2765564) | Cod sursa (job #2697661)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int n, m;
vector<int> G[1005];
int capacity[1005][1005];
vector<int> bfs(int from, int to) {
vector<int> parent(n + 1);
queue<int> q;
q.push(from);
parent[from] = -1;
while (!q.empty()) {
int current = q.front();
q.pop();
for (int x : G[current]) {
if (!parent[x] && capacity[current][x]) {
q.push(x);
parent[x] = current;
}
}
}
if (parent[to] == 0)
return {};
vector<int> ret;
int p = to;
while (p > 0) {
ret.push_back(p);
p = parent[p];
}
reverse(ret.begin(), ret.end());
return ret;
}
int flux(int from, int to) {
int ret = 0;
while (true) {
vector<int> path = bfs(from, to);
if (path.size() == 0)
break;
int current = (1 << 30);
for (int i = 1; i < path.size(); i++) {
current = min(current, capacity[path[i - 1]][path[i]]);
}
for (int i = 1; i < path.size(); i++) {
capacity[path[i - 1]][path[i]] -= current;
capacity[path[i]][path[i - 1]] += current;
}
ret += current;
}
return ret;
}
int main() {
in >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y, c;
in >> x >> y >> c;
G[x].push_back(y);
G[y].push_back(x);
capacity[x][y] = c;
}
out << flux(1, n);
}