Pagini recente » Cod sursa (job #1113674) | Cod sursa (job #139858) | Cod sursa (job #2876964) | Cod sursa (job #380439) | Cod sursa (job #2875781)
#include <bits/stdc++.h>
using namespace std;
int dfs(int node, const int& DEST, int minDelta, vector<bool>& vis,
vector<vector<int>>& g, vector<vector<int>>& c, vector<vector<int>>& f){
if(vis[node]){
return 0;
}
vis[node] = true;
if(node == DEST){
return minDelta;
}
for(int nextNode: g[node]){
int delta = c[node][nextNode] - f[node][nextNode];
if(delta > 0){
int flow = dfs(nextNode, DEST, min(minDelta, delta), vis, g, c, f);
if(flow > 0){
f[node][nextNode] += flow;
f[nextNode][node] -= flow;
return flow;
}
}
}
return 0;
}
int computeMaxFlow(vector<vector<int>>& g, vector<vector<int>>& c,
const int& SRC, const int& DEST){
const int N = g.size();
vector<vector<int>> f(N, vector<int>(N));
vector<bool> vis(N);
int maxFlow = 0;
while(true){
fill(vis.begin(), vis.end(), false);
int delta = dfs(SRC, DEST, INT_MAX, vis, g, c, f);
if(delta > 0){
maxFlow += delta;
}else{
break;
}
}
return maxFlow;
}
int main(){
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
int N, M;
cin >> N >> M;
vector<vector<int>> g(N);
vector<vector<int>> c(N, vector<int>(N));
int x, y;
for(int i = 0; i < M; ++i){
cin >> x >> y;
--x;
--y;
cin >> c[x][y];
g[x].push_back(y);
g[y].push_back(x);
}
srand(time(NULL));
for(int node = 0; node < N; ++node){
random_shuffle(g[node].begin(), g[node].end());
}
cout << computeMaxFlow(g, c, 0, N - 1);
cin.close();
cout.close();
return 0;
}