Pagini recente » Cod sursa (job #2410199) | Cod sursa (job #545974) | Cod sursa (job #127535) | Cod sursa (job #2011321) | Cod sursa (job #2957566)
#include <bits/stdc++.h>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
class Solution {
int n, m;
vector<vector<int>> capacity, flow, adj;
vector<bool> viz;
vector<int> parent;
public:
Solution(int _n, int _m, vector<tuple<int, int, int>> edges);
bool bfs(int src);
int findMaxFlow();
};
bool Solution::bfs(int src) {
fill(viz.begin(), viz.end(), false);
fill(parent.begin(), parent.end(), 0);
queue<int> q;
q.push(src);
viz[src] = true;
int currNode;
while(!q.empty()) {
currNode = q.front();
q.pop();
for(auto nextNode : adj[currNode])
if(!viz[nextNode] && capacity[currNode][nextNode] - flow[currNode][nextNode] > 0) {
viz[nextNode] = true;
if(nextNode != n) {
q.push(nextNode);
parent[nextNode] = currNode;
}
}
}
return viz[n];
}
int Solution::findMaxFlow() {
int maxFlow = 0;
while(bfs(1)) {
for(auto leaf : adj[n]) {
if(capacity[leaf][n] - flow[leaf][n] <= 0 || !viz[leaf])
continue;
// find the minimum capacity-flow value on the path
parent[n] = leaf;
int minValOnPath = 110000;
for(int node = n; parent[node]; node = parent[node])
minValOnPath = min(minValOnPath, capacity[parent[node]][node] - flow[parent[node]][node]);
if(!minValOnPath)
continue;
maxFlow += minValOnPath;
// update flow on path
for(int node = n; parent[node]; node = parent[node]) {
flow[parent[node]][node] += minValOnPath;
flow[node][parent[node]] -= minValOnPath;
}
}
}
return maxFlow;
}
Solution::Solution(int _n, int _m, vector<tuple<int, int, int>> edges) {
n = _n;
m = _m;
adj.resize(n + 1);
viz.resize(n + 1, false);
parent.resize(n + 1, 0);
capacity.resize(n + 1, vector<int>(n + 1, 0));
flow.resize(n + 1, vector<int>(n + 1, 0));
int x, y, c;
for(auto& edge : edges) {
x = get<0>(edge); y = get<1>(edge); c = get<2>(edge);
capacity[x][y] = c;
adj[x].push_back(y);
adj[y].push_back(x);
}
}
int main() {
vector<tuple<int, int, int>> edges;
int n, m, x, y, c;
in >> n >> m;
while(m --) {
in >> x >> y >> c;
edges.push_back({x, y, c});
}
Solution s(n, m, edges);
out << s.findMaxFlow();
return 0;
}