hdu 3987 Harry Potter and the Forbidden Forest

来源:互联网 发布:冰川网络 游戏 编辑:程序博客网 时间:2024/05/18 09:03

【分析】
网络流好题


【代码】

#include<queue>#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#define ll long long#define inf 1e16#define M(a) memset(a,0,sizeof a)#define fo(i,j,k) for(i=j;i<=k;i++)using namespace std;const int mxn=1000005;queue <int> q;ll ans;int s,t,n,m,T,cnt;int x[mxn],y[mxn],c[mxn];struct edge {int to,next,flow,from;} f[mxn<<1];int head[mxn],dis[mxn];inline void add(int u,int v,int flow){    f[++cnt].to=v,f[cnt].from=u,f[cnt].next=head[u],f[cnt].flow=flow,head[u]=cnt;    f[++cnt].to=u,f[cnt].from=v,f[cnt].next=head[v],f[cnt].flow=0,head[v]=cnt;}inline bool bfs(){    memset(dis,-1,sizeof dis);    q.push(s);dis[s]=0;    while(!q.empty())    {        int u=q.front();        q.pop();        for(int i=head[u];i;i=f[i].next)        {            int v=f[i].to;            if(dis[v]==-1 && f[i].flow>0)              dis[v]=dis[u]+1,q.push(v);        }    }    return dis[t]>0;}inline ll find(int u,ll low){    if(u==t) return low;    ll sum=0,a=0;    for(int i=head[u];i;i=f[i].next)    {        int v=f[i].to;ll flow=f[i].flow;        if( dis[v]==dis[u]+1 && flow>0 && (a=find(v,min(flow,low-sum))) )        {            sum+=a;            f[i].flow-=a;            if(i&1) f[i+1].flow+=a;            else f[i-1].flow+=a;        }    }    if(!sum) dis[u]=-1;    return sum;}int main(){    int i,j,u,r,v,c,d;    scanf("%d",&T);    fo(r,1,T)    {        scanf("%d%d",&n,&m);        s=0,t=n-1,cnt=ans=0;        M(head),M(dis),M(f);        fo(i,1,m)        {            scanf("%d%d%d%d",&u,&v,&c,&d);            add(u,v,c);            if(d) add(v,u,c);        }        while(bfs()) find(s,inf);        for(i=1;i<=cnt;i+=2)          if(f[i].flow==0)            f[i].flow=1,f[i+1].flow=0;          else            f[i].flow=1e9+7,f[i+1].flow=0;        while(bfs()) ans+=find(s,inf);        printf("Case %d: %lld\n",r,ans);    }    return 0;}
1 0