回顾一下Dinic,还是优化了的,确实要快一点,这个0ms,原来EK算法是15ms.很基础就不讲了。倒是有点感悟到Dinic好在哪里了。再写!
代码:
#include<iostream> using namespace std; #define INF 0x7fffffff #define maxn 205 struct Edge { int v,f,next; } e[2*maxn]; bool visit[maxn]; int level[maxn],que[maxn],head[maxn]; int s=1,t,size; bool BFS() { memset(visit,0,sizeof(visit)); memset(level,0,sizeof(level)); int first,rear,u,v,i; first=rear=0; que[rear++]=s; level[s]=1; while( first!=rear){ u=que[first++]; if( u==t) return true; for( i=head[u]; i!=-1; i=e[i].next){ v=e[i].v; if( !level[v]&&e[i].f){ level[v]=level[u]+1; que[rear++]=v; } } } return false; } void AddEdge(int a,int b,int c) { e[size].v=b; e[size].f=c; e[size].next=head[a]; head[a]=size++; } int DFS(int u,int mimf) { if( u==t) return mimf; int ret,f,i; ret=0; for( i=head[u]; i!=-1; i=e[i].next){ if( e[i].f&&level[e[i].v]==level[u]+1){ f=DFS(e[i].v,min(mimf-ret,e[i].f)); e[i].f-=f; e[i^1].f+=f; ret+=f; if( mimf==ret) return ret; } } return ret; } int main() { int n,m,a,b,c,ret; while( scanf("%d%d",&m,&n)!=EOF){ size=0; s=1; t=n; memset(e,0,sizeof(e)); memset(head,-1,sizeof(head)); while( m--){ scanf("%d%d%d",&a,&b,&c); AddEdge(a,b,c); AddEdge(b,a,0); } ret=0; while( BFS()){ ret+=DFS(s,INF); } printf("%d\n",ret); } return 0; }