Pagini recente » Cod sursa (job #1732877) | Cod sursa (job #961981) | Cod sursa (job #1271495) | Cod sursa (job #403250) | Cod sursa (job #1976429)
#include <bits/stdc++.h>
using namespace std;
template <class T, size_t INF=0x3f3f3f3f>
class MaxFlow {
typedef vector<vector<size_t>> Graph;
typedef unordered_map<size_t, unordered_map<size_t, T>> SparseMatrix;
T flow_val_;
Graph graph_;
SparseMatrix capacity_;
SparseMatrix flow_;
public:
MaxFlow(size_t n) {
graph_.resize(n + 1);
}
void add_edge(size_t x, size_t y, T c) {
graph_[x].push_back(y);
graph_[y].push_back(x);
capacity_[x][y] += c;
capacity_[y][x] += 0;
}
vector<size_t> bfs(size_t start, size_t finish) {
vector<bool> visited(graph_.size(), false);
vector<size_t> parent(graph_.size(), 0);
queue<size_t> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
size_t node = q.front(); q.pop();
if (node == finish) {
continue;
}
for (int neigh : graph_[node]) {
if (flow_[node][neigh] < capacity_[node][neigh] && !visited[neigh]) {
parent[neigh] = node;
visited[neigh] = true;
q.push(neigh);
}
}
}
return parent;
}
int do_flow(int start, int finish) {
int flow = 0;
while (true) {
auto parent = bfs(start, finish);
if (parent[finish] == 0) {
break;
}
for (size_t neigh : graph_[finish]) {
if (flow_[neigh][finish] == capacity_[neigh][finish] || parent[neigh] == 0) {
continue;
}
T fmin = INF;
parent[finish] = neigh;
for (size_t node = finish; node != start; node = parent[node]) {
fmin = min(fmin, capacity_[parent[node]][node] - flow_[parent[node]][node]);
}
if (fmin == 0) {
continue;
}
for (size_t node = finish; node != start; node = parent[node]) {
flow_[parent[node]][node] += fmin;
flow_[node][parent[node]] -= fmin;
}
flow += fmin;
}
}
flow_val_ = flow;
return flow;
}
SparseMatrix get_flow() {
return flow_;
}
};
int main() {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
int n, m;
cin >> n >> m;
MaxFlow<int> flow(n);
for (int i = 1; i <= m; ++ i) {
int x, y, c;
cin >> x >> y >> c;
flow.add_edge(x, y, c);
}
cout << flow.do_flow(1, n) << endl;
return 0;
}