Pagini recente » Cod sursa (job #3166724) | Cod sursa (job #549962) | Cod sursa (job #975722) | Cod sursa (job #2837562) | Cod sursa (job #2746353)
#include <bits/stdc++.h>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
bool bfs(int s, int t, vector<int> &father, vector<vector<int> > &capacity, vector<vector<int> > &flow, vector<vector<int> > &adj){
//set all fathers to -1
//create the tree
fill(father.begin(), father.end(), -1);
queue<int> q;
father[s] = s;
q.push(s);
while(!q.empty()){
int u = q.front();
q.pop();
for(auto v: adj[u]){
if(capacity[u][v] > flow[u][v] && father[v] == -1){
father[v] = u;
q.push(v);
}
}
}
return father[t] != -1;
}
int max_flow(int s, int t, vector<vector<int> > &capacity, vector<vector<int> > &flow, vector<vector<int> > &adj){
//adj has both edges x -> y; y -> x
//if flow has a low demand flow[x][y] > sth, just set the initial value of the flow
//to that value
int total = 0;
vector<int> father(adj.size());
while(bfs(s, t, father, capacity, flow, adj)){
for(auto u: adj[t]){
if(father[u] == -1) continue;
int current_flow = capacity[u][t] - flow[u][t];
for(int v = u; v != s; v = father[v]){
int w = father[v];
current_flow = min(current_flow, capacity[w][v] - flow[w][v]);
}
flow[u][t] += current_flow;
flow[t][u] -= current_flow;
for(int v = u; v != s; v = father[v]){
int w = father[v];
flow[w][v] += current_flow;
flow[v][w] -= current_flow;
}
total += current_flow;
}
}
return total;
}
int main(){
int n,m;
in >> n >> m;
vector<vector<int> > adj;
vector<vector<int> > capacity;
vector<vector<int> > flow;
adj.resize(n+1);
capacity.resize(n+1);
flow.resize(n+1);
for(int i=1; i<=n; i++){
capacity[i].resize(n+1, 0);
flow[i].resize(n+1, 0);
}
for(int i=0; i<m; i++){
int x, y;
in >> x >> y;
if(!capacity[x][y] && !capacity[y][x]){
adj[x].push_back(y);
adj[y].push_back(x);
}
in >> capacity[x][y];
}
out << max_flow(1,n,capacity,flow,adj) << '\n';
return 0;
}