【poj 1273】Drainage Ditches 最大流dinic模板

来源:互联网 发布:js数组重排序 编辑:程序博客网 时间:2024/05/22 02:10

唯一的坑点就是居然是多组数据,wa了一次

以前都是写的sap但是后来看了黄学长的dinic模板,感觉很快就学(狼爪兔子拿到毒瘤题我的sap狂T不止,最后还是向恶势力低头,用了对偶图跑spfa,但是人家直接硬刚dinic,而且。。。。比我的spfa块),但是速度上其实和图有关,例如那道黄学长网站上的【East!_XVI】九尾妖狐 glk的sap比我快了0.1秒(为什么受伤的都是我)

SAP模板(短速度还不错):http://blog.csdn.net/pbihao/article/details/52444079

#include<cstdio>#include<cstring>#include<iostream>#define maxn 500#define LL long longusing namespace std;LL n,m,head[maxn],tot,s,t,last[maxn],ans,h[maxn],q[maxn];struct edge{LL v,next,w;}e[maxn*maxn];void adde(LL a,LL b,LL c){e[tot].v=b,e[tot].w=c,e[tot].next=head[a];head[a]=tot++;}bool bfs(){LL l=0,r=1;for(LL i=1;i<=t;i++)h[i]=-1;h[s]=0,q[0]=s;while(l!=r){LL u=q[l++];for(LL i=head[u];i!=-1;i=e[i].next){LL v=e[i].v;if(h[v]==-1&&e[i].w){h[v]=h[u]+1;q[r++]=v;}}}return h[t]!=-1;}LL dfs(LL u,LL f){if(u==t)return f;LL w,used=0;for(LL i=last[u];i!=-1;i=e[i].next){LL v=e[i].v;if(h[v]!=h[u]+1)continue;if(e[i].w)last[u]=i;w=f-used;w=dfs(v,min(w,e[i].w ));e[i].w-=w,e[i^1].w+=w;used+=w;if(used==f)return f;}if(!used)h[u]=-1;return used;}int main(){while(scanf("%lld%lld",&n,&m)!=EOF){ans=0;memset(head,-1,sizeof(head));s=1,t=m,tot=0;for(LL a,b,c,i=1;i<=n;i++){scanf("%lld%lld%lld",&a,&b,&c);adde(a,b,c),adde(b,a,0);}while(bfs()){for(LL i=0;i<=t;i++)last[i]=head[i];ans+=dfs(s,1e9);}printf("%lld\n",ans);}return 0;} 


0 0