Pagini recente » Cod sursa (job #368743) | Cod sursa (job #446870) | Cod sursa (job #657933) | Cod sursa (job #2104441) | Cod sursa (job #2939614)
///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;
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 next:edges[node])
if(graph[node][next].capacity-graph[node][next].flow>0 && level[next]==-1)///if I can still push flow and the node is not visited
{
level[next]=level[node]+1;
q.push(next);
}
}
return level[t]!=-1;///if t was visited it will return 1,otherwise 0
}
int dfs(int node,int t,int cur_flow)
{
if(cur_flow==0)
return 0;
if(node==t)
return cur_flow;
for(int& i=skip[node]; i<edges[node].size(); i++)///thanks to the reference, the skip vector will also change
{
int next=edges[node][i];
if(graph[node][next].capacity-graph[node][next].flow>0 && level[node]+1==level[next])///if I can still push flow and the node is not visited and we only go forward
{
cur_flow=min(cur_flow,graph[node][next].capacity-graph[node][next].flow);
int bottleNeck=dfs(next,t,cur_flow);
if(bottleNeck>0)
{
graph[node][next].flow+=bottleNeck;///update on the normal edge
graph[next][node].flow-=bottleNeck;///update on the reverse edge
return bottleNeck;
}
}
}
return 0;
}
int maxflow(int s,int t)
{
int max_flow=0;
skip.resize(n+1);
while(bfs(s,t))
{
fill(skip.begin(),skip.end(),0);///for pruning dead ends
for(int new_flow=dfs(s,t,INF); new_flow!=0; new_flow=dfs(s,t,INF))
max_flow+=new_flow;
}
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;
}