hdu 1532 Dinic 模板 0是原点m是汇点
我纠结了四天的网络流,看疯了各种网络流的基础课件,各种参考书,看的是云里雾里
最后还是做题一点不懂,最后一个模板解决问题,神啊
这里体现了模板的强大力量
#include <stdio.h> #include <string.h> const int maxn=150000; const int maxm=200000; const int inf=1<<30; struct edge { int from,to,val,next; }map[maxn]; int vis[maxn],que[maxn],dist[maxn],len; void init() { len=0; memset(vis,-1,sizeof(vis)); } void insert (int from,int to,int val) { map[len].from=from; map[len].to=to; map[len].val=val; map[len].next=vis[from]; vis[from]=len++; map[len].from=to; map[len].to=from; map[len].val=0; map[len].next=vis[to]; vis[to]=len++; } int Dinic(int n,int s,int t) { int ans=0; while(true) { int head,tail,id,i; head=tail=0; que[tail++]=s; memset(dist,-1,sizeof(dist)); dist[s]=0; while(head<tail) { id=vis[que[head++]]; while(id!=-1) { if(map[id].val>0&&dist[map[id].to]==-1) { dist[map[id].to]=dist[map[id].from]+1; que[tail++]=map[id].to; if(map[id].to==t) { head=tail; break; } } id=map[id].next; } } if(dist[t]==-1) break; id=s,tail=0; while(true) { if(id==t) //找到一条增广路 { int flow=inf,fir; for(i=0;i<tail;i++) if(map[que[i]].val<flow) { fir=i; flow=map[que[i]].val; } for(i=0;i<tail;i++) { map[que[i]].val-=flow; map[que[i]^1].val+=flow; } ans+=flow; tail=fir; id=map[que[fir]].from; } id=vis[id]; while(id!=-1) { if(map[id].val>0&&dist[map[id].from]+1==dist[map[id].to]) break; id=map[id].next; } if(id!=-1) { que[tail++]=id; id=map[id].to; } else { if(tail==0) break; dist[map[que[tail-1]].to]=-1; id=map[que[--tail]].from; } } } return ans; } int main() { int n,m,i; int s,e,a; while(scanf("%d%d",&m,&n)!=EOF) { init(); for(i=0;i<m;i++) { scanf("%d%d%d",&s,&e,&a); insert(s,e,a); } printf("%d\n",Dinic(n,1,n)); } return 0; }