Pagini recente » Cod sursa (job #3237542) | Cod sursa (job #2159334) | Cod sursa (job #682959) | Cod sursa (job #2658805) | Cod sursa (job #2939092)
//Max Flow Ford-Fulkerson
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
const int NMAX=1005,INF=0x3F3F3F3F;
int n,m,x,y,c,new_flow;
struct flux
{
int flow,capacity;
} graph[NMAX][NMAX];
vector<int>parent;
void dfs(int node,int t,int cur_flow)
{
for(int i=1; i<=n; i++)
if((graph[node][i].capacity-graph[node][i].flow)>0 && parent[i]==-1)///if I can still push at least one unit of flow and the node is not visited
{
cur_flow=min(cur_flow,graph[node][i].capacity-graph[node][i].flow);///second parameter is the number of units of flow I can push through this edge
parent[i]=node;
if(i==t)
{
new_flow=cur_flow;
t=-1;///we shouldn't reach it after the finding a path
}
dfs(i,t,cur_flow);
}
}
int max_flow(int s,int t)///source, terminal
{
int flow=0,curr,prev;
while(1)
{
new_flow=0;
parent.assign(n+1,-1);
parent[s]=-2;///so that we cannot reach it afterwards
dfs(s,t,INF);///this generates a new flow
if(new_flow==0)
break;
flow+=new_flow;
curr=t;
while(curr!=s)
{
prev=parent[curr];
graph[prev][curr].flow+=new_flow;///update on the normal edge
graph[curr][prev].flow-=new_flow;///update on the reverse edge
curr=prev;
}
}
return flow;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
f>>n>>m;
for(int i=1; i<=m; i++)
{
f>>x>>y>>c;
graph[x][y].capacity=c;///graph[x][y].flow=0 already
}
g<<max_flow(1,n);///source, terminal
return 0;
}