Pagini recente » Cod sursa (job #895763) | Cod sursa (job #2102495) | Cod sursa (job #1128891) | Cod sursa (job #3164080) | Cod sursa (job #2767931)
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
const int NMAX = 1e3;
int s, d;
std::vector<int> graph[1 + NMAX];
int cap[1 + NMAX][1 + NMAX];
bool vis[1 + NMAX];
int t[1 + NMAX];
std::queue<int> q;
std::vector<int> paths;
bool bfs() {
memset(vis, 0, sizeof(vis));
paths.clear();
q.push(s);
while (!q.empty()) {
int node = q.front();
q.pop();
for (auto& nb : graph[node]) {
if (!vis[nb] && cap[node][nb] > 0) {
t[nb] = node;
if (nb == d) {
paths.push_back(node);
continue;
}
vis[nb] = true;
q.push(nb);
}
}
}
return !paths.empty();
}
int main() {
std::ifstream in("maxflow.in");
std::ofstream out("maxflow.out");
int n, m;
in >> n >> m;
for (int i = 1; i <= m; ++i) {
int x, y, c;
in >> x >> y >> c;
graph[x].push_back(y);
graph[y].push_back(x);
cap[x][y] += c;
}
s = 1;
d = n;
int maxFlow = 0;
while (bfs()) {
for (auto start : paths) {
int min = 1e9;
t[d] = start;
for (int current = d; current != s; current = t[current])
min = std::min(min, cap[t[current]][current]);
for (int current = d; current != s; current = t[current]) {
cap[t[current]][current] -= min;
cap[current][t[current]] += min;
}
maxFlow += min;
}
}
out << maxFlow << '\n';
return 0;
}