A Brief Discussion on Current Arc Optimization of Network Flow

In dinic, we will find that each edge in dfs will be traversed at least once, so can we delete the edge that must not be used?

The answer is of course, this uses the current arc optimization;

In fact, this optimization came into contact with the Euler circuit a long time ago;

Each time a road is enlarged, it can be regarded as "squeezing dry" the road. Since it is drained, there is no possibility of further expansion. But it's a waste of time to scan these "withered" edges every time. Then we record the "extraction" to that edge, and then directly start from this edge next time, which can save a lot of time. This is the current arc optimization .

The implementation method is to copy the head array every time dfs, and then run dfs in the new array

#include <bits/stdc++.h>
#define int long long
using namespace std;
struct littlestar{
	int to;
	int nxt;
	int w;
}star[10010];
int head[10010],cur[10010],cnt=1;
void add(int u,int v,int w)
{
	star[++cnt].to=v;
	star[cnt].nxt=head[u];
	star[cnt].w=w;
	head[u]=cnt;
}
int s,t;
queue<int> q;
int n;
int dep[10010];
bool bfs()
{
	for(int i=1;i<=n;i++){
		dep[i]=0;
		cur[i]=head[i];
	}
	while(q.size()) q.pop();
	q.push(s);
	dep[s]=1;
	while(q.size()){
		int u=q.front();
		q.pop();
		for(int i=head[u];i;i=star[i].nxt){
			int v=star[i].to;
			if(!dep[v]&&star[i].w){
				dep[v]=dep[u]+1;
				q.push(v);
				if(v==t) return 1;
			}
		}
	}
	return 0;
}
int m;
int dinic(int u,int flow)
{
	if(u==t) return flow;
	int rest=flow,tmp;
	for(int i=cur[u];i&&rest;i=star[i].nxt){
		cur[u]=i;
		int v=star[i].to;
		if(dep[v]==dep[u]+1&&star[i].w){
			tmp=dinic(v,min(star[i].w,rest));
			if(!tmp) dep[v]=0;
			star[i].w-=tmp;
			star[i^1].w+=tmp;
			rest-=tmp;
		}
	}
	return flow-rest;
}
signed main()
{
	cin>>n>>m>>s>>t;
	for(register int i=1;i<=m;i++){
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		add(u,v,w);
		add(v,u,0);
	}
	int maxflow=0;
	while(bfs()){
		int flow;
		while(flow=dinic(s,LLONG_MAX)) maxflow+=flow;
	}
	cout<<maxflow;
}

 

Reprinted in: https://www.cnblogs.com/kamimxr/p/11607636.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326472766&siteId=291194637