Pagini recente » Cod sursa (job #3310093) | Cod sursa (job #3328640) | Cod sursa (job #2118983) | Cod sursa (job #808518) | Cod sursa (job #3336951)
#include <cstdio>
#include <iostream>
#include <limits>
#include <queue>
#include <vector>
class FlowNetwork {
public:
FlowNetwork(int n)
: n(n), capacity(n, std::vector<int>(n)) {}
void add_edge(int u, int v, int c) {
capacity[u][v] += c;
}
int flow(int source, int destination) {
int flow = 0;
std::vector<int> parent(n);
while (bfs(source, destination, parent)) {
int flow_to_add = std::numeric_limits<int>::max();
for (int v = destination; v != source; v = parent[v]) {
flow_to_add = std::min(flow_to_add, capacity[parent[v]][v]);
}
for (int v = destination; v != source; v = parent[v]) {
capacity[parent[v]][v] -= flow_to_add;
capacity[v][parent[v]] += flow_to_add;
}
flow += flow_to_add;
}
return flow;
}
private:
bool bfs(int source, int destination, std::vector<int>& parent) {
std::vector<bool> visited(n);
std::queue<int> que;
que.push(source); visited[source] = true;
while (!que.empty()) {
int u = que.front(); que.pop();
if (u == destination) {
continue;
}
for (int v = 0; v < n; v++) {
if (!visited[v] && capacity[u][v] > 0) {
visited[v] = true;
parent[v] = u;
que.push(v);
}
}
}
return visited[destination];
}
int n;
std::vector<std::vector<int>> capacity;
};
int main() {
std::freopen("maxflow.in", "r", stdin);
std::freopen("maxflow.out", "w", stdout);
int n, m;
std::cin >> n >> m;
FlowNetwork network(n);
for (int i = 0; i < m; i++) {
int u, v, c;
std::cin >> u >> v >> c;
network.add_edge(u - 1, v - 1, c);
}
std::cout << network.flow(0, n - 1) << "\n";
return 0;
}