Pagini recente » Cod sursa (job #2904040) | Cod sursa (job #51039) | Cod sursa (job #52721) | Cod sursa (job #814552) | Cod sursa (job #2940066)
///Max Flow Dinic's Algorithm with scaling
///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,maxx;
bool SCALING=1;
struct edge
{
int node, flow, capacity, index;
};
vector<int>level,skip;
vector<edge>edges[NMAX];
bool bfs(int s,int t,int limit)
{
level.assign(n+1,-1);
level[s]=0;
queue<int>q;
q.push(s);
while(!q.empty())
{
int node=q.front();
q.pop();
for(edge& link:edges[node])
if(link.capacity-link.flow>0 && level[link.node]==-1 && (!SCALING || link.capacity-link.flow>=limit))///if I can still push flow and the next node is not visited
{
level[link.node]=level[node]+1;
q.push(link.node);
}
}
return level[t]!=-1;///if t was visited it will return 1,otherwise 0
}
int dfs(int node,int t,int cur_flow)
{
if(node==t)
return cur_flow;
for(; skip[node]<edges[node].size(); skip[node]++)///we start from the pointer we have for this node
{
int next=edges[node][skip[node]].node;
edge& link = edges[node][skip[node]];///for simplicity
if(link.capacity-link.flow>0 && level[node]+1==level[next])///if I can still push flow and the node is not visited and we only go forward
{
int bottleNeck=dfs(next,t,min(cur_flow,link.capacity-link.flow));
if(bottleNeck>0)
{
link.flow+=bottleNeck;///update on the normal edge
edges[next][link.index].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);
for(int limit=SCALING ? (1<<(int(log2(maxx)))):1; limit>0; limit=limit/2)
while(bfs(s,t,limit))
{
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))///as long as we can find a new path we increase the max_flow
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;
edges[x].push_back({y,0,c,0});///to node,flow,capacity,index
edges[y].push_back({x,0,0,0});///reverse edge:to node,flow,capacity,index
edges[x].back().index=edges[y].size()-1;///index from adjacency list of y
edges[y].back().index=edges[x].size()-1;///index from adjacency list of x
if(c>maxx)
maxx=c;
}
g<<maxflow(1,n);///source, terminal
return 0;
}