Pagini recente » Cod sursa (job #1666345) | Cod sursa (job #2452131) | Cod sursa (job #1389909) | Cod sursa (job #3222595) | Cod sursa (job #2939546)
///Max Flow Dinic's Algorithm
///O(N*N*M) on normal graphs
///O(sqrt(N)*M) on bipartite graphs
#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>level,parent,skip,edges[NMAX];
bool bfs(int s,int t)
{
level.assign(n+1,-1);
level[s]=0;
queue<int>q;
q.push(s);
while(!q.empty())
{
int node=q.front();
q.pop();
for(int i=0; i<edges[node].size(); i++)
if(graph[node][edges[node][i]].capacity-graph[node][edges[node][i]].flow>0 && level[edges[node][i]]==-1)///if I can still push flow and the node is not visited
{
level[edges[node][i]]=level[node]+1;
q.push(edges[node][i]);
}
}
return level[t]!=-1;///if t was visited it will return 1,otherwise 0
}
void dfs(int node,int t,int cur_flow)
{
for(int& i=skip[node]; i<edges[node].size() && t>0; i++) //thanks to the reference, the skip vector will also change
if(graph[node][edges[node][i]].capacity-graph[node][edges[node][i]].flow>0 && parent[edges[node][i]]==-1 && level[node]+1==level[edges[node][i]])
///if I can still push flow and the node is not visited and we only go forward
{
cur_flow=min(cur_flow,graph[node][edges[node][i]].capacity-graph[node][edges[node][i]].flow);
parent[edges[node][i]]=node;
if(edges[node][i]==t)
{
new_flow=cur_flow;
t=-1;//we should not reach it after finding a path
}
dfs(edges[node][i],t,cur_flow);
}
}
int maxflow(int s,int t)
{
int max_flow=0,curr,prev;
parent.resize(n+1);
skip.resize(n+1);
while(bfs(s,t))
{
fill(parent.begin(),parent.end(),-1);
parent[s]=-2;
fill(skip.begin(),skip.end(),0);
while(1)
{
new_flow=0;
dfs(s,t,INF);
if(new_flow==0)
break;
max_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 max_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
edges[x].push_back(y);
}
g<<maxflow(1,n);///source, terminal
return 0;
}