Pagini recente » Cod sursa (job #343634) | Cod sursa (job #974436) | Cod sursa (job #2549265) | Cod sursa (job #1935919) | Cod sursa (job #1872794)
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <utility>
#include <cstdlib>
#include <algorithm>
typedef std::vector<std::pair<int, int> > graph_node;
typedef std::vector<graph_node > graph;
typedef std::map < int, std::pair<int, int> > flow_node;
typedef std::vector < flow_node > flow_graph;
graph g;
bool relabel(int nod, flow_graph &r, std::vector<int> &l, std::vector<int> &x) {
int min = r.size() + 1;
for (auto it : r[nod]) {
if (l[it.first] < min && it.second.first > it.second.second)
min = l[it.first];
}
if (x[nod] > 0 && l[nod] <= min && min != r.size () + 1) {
l[nod] = min + 1;
return true;
}
else {
return false;
}
}
bool push(int nod, int next, flow_graph &r, std::vector<int> &l, std::vector<int> &x) {
if (x[nod] > 0 && l[nod] == l[next] + 1 && next != 1) {
int d = std::min(x[nod], r[nod][next].first - r[nod][next].second);
if (d == 0) return false;
r[nod][next].second += d;
r[next][nod].second -= d;
x[nod] -= d;
x[next] += d;
return true;
}
return false;
}
int max_flow(graph &g, int source, int dest) {
flow_graph r(g.size (), flow_node ());
for (int i = 1; i < g.size (); i++) {
for (auto it : g[i]) {
r[i][it.first] = {it.second, 0};
}
}
std::vector<int> l(r.size(), 0);
std::vector<int> x(r.size(), 0);
l[source] = r.size ();
for (auto& it : r[source]) {
it.second.second += it.second.first;
r[it.first][source].second -= it.second.first;
x[it.first] += it.second.first;
}
bool op = true;
while (op) {
op = false;
for (int i = 1; i < r.size(); i++) {
op |= relabel(i, r, l, x);
for (auto it : r[i]) {
op |= push(i, it.first, r, l, x);
}
}
}
int sum = 0;
for (auto& it : r[source]) {
sum += it.second.second;
}
return sum;
}
int main() {
int n, m, x, y, c;
std::ifstream cin("maxflow.in");
std::ofstream cout("maxflow.out");
cin >> n >> m;
g = std::vector< graph_node >(n + 1, graph_node());
for (int i = 0; i < m; i++) {
std::cin >> x >> y >> c;
g[x].push_back({ y, c });
}
cout << max_flow(g, 1, n);
return 0;
}