DINIC(无当前弧优化):
void add(int x,int y,int z){
son[++tot]=y,w[tot]=z,nxt[tot]=lnk[x],lnk[x]=tot;
}
int dfs(int x,int sum){
if (x==T) return sum;
for (int j=lnk[x];j!=-1;j=nxt[j])
if (dep[son[j]]==dep[x]+1&&w[j]!=0) {
int sum1=dfs(son[j],min(sum,w[j]));
if (sum1>0) {w[j]-=sum1,w[j^1]+=sum1; return sum1;}
}
return 0;
}
int bfs(){
memset(dep,0,sizeof(dep));
int head=0,tail=1; que[tail]=S,dep[1]=1;
while (head!=tail) {
head++;
for (int j=lnk[que[head]];j!=-1;j=nxt[j])
if (w[j]>0&&dep[son[j]]==0)
dep[son[j]]=dep[que[head]]+1,que[++tail]=son[j];
}
if (dep[T]>0) return 1; else return 0;
}
int dinic(){
int sum;
while (bfs()) {
while (sum=dfs(S,inf)) ans+=sum;
}
return ans;
}
DINIC(含当前弧优化)
多了一个cur数组,很好理解。
int bfs(){
memset(dep,0,sizeof(dep));
int head=0,tail=1; que[tail]=S,dep[S]=1;
while (head!=tail) {
head++;
for (int j=lnk[que[head]];j!=-1;j=nxt[j])
if (dep[son[j]]==0&&w[j]>0)
dep[son[j]]=dep[que[head]]+1,que[++tail]=son[j];
}
return dep[T];
}
int dfs(int x,int sum){
if (x==T) return sum;
for (int& j=cur[x];j!=-1;j=nxt[j])
if (w[j]>0&&dep[son[j]]==dep[x]+1) {
int sum1=dfs(son[j],min(sum,w[j]));
if (sum1>0) {w[j]-=sum1,w[j^1]+=sum1; return sum1;}
}
return 0;
}
int dinic(){
while (bfs()) {
for (int i=1;i<=T;i++) cur[i]=lnk[i];
int sum; while (sum=dfs(S,inf)) ans-=sum;
}
return ans;
}
例题:
经典模板题:
POJ1273
HihoCoder1369