bzoj1001: [BeiJing2006]狼抓兔子(最大流)

来源:互联网 发布:哪个清理软件最好 编辑:程序博客网 时间:2024/06/05 14:55

题目传送门

解法:
每一只兔子就需要一只狼。
那么我们只需要求出最多能通过多少只兔子即可。
然后就派多少只狼就行了呗。。
因为兔子从哪里过来的我就在哪里放狼。
所以狼的数量一定等于最多兔子通过的数量
题目并不要求求方案,所以不需知道兔子从哪过来。

所以直接建边跑最大流就OK了。
注:因为是双向边所以反向边流量等于正向边流量。

代码实现:

#include<cstdio>#include<cstring>#include<cstdlib>#include<iostream>#include<algorithm>using namespace std;struct node {    int x,y,c,next,other;}a[6100000];int len,last[1100000]; //注意数组大小。边应该是3000000*2.我一开始开小了没发现。void ins(int x,int y,int c) {    int k1,k2;    len++;k1=len;    a[len].x=x;a[len].y=y;a[len].c=c;    a[len].next=last[x];last[x]=len;    len++;k2=len;    a[len].x=y;a[len].y=x;a[len].c=c; //反向边流量等于c    a[len].next=last[y],last[y]=len;    a[k1].other=k2;    a[k2].other=k1;}int list[1100000],head,tail;int st,ed,n,h[1100000];bool bfs() {    memset(h,0,sizeof(h));h[st]=1;    head=1;tail=2;list[1]=st;    while(head!=tail) {        int x=list[head];        for(int k=last[x];k;k=a[k].next) {            int y=a[k].y;            if(h[y]==0&&a[k].c>0) {                h[y]=h[x]+1;                list[tail++]=y;                if(tail==ed+1)                    tail=1;            }        }        head++;        if(head==ed+1)            head=1;    }    if(h[ed]==0)        return false;    return true;}int findflow(int x,int f) {    if(x==ed)        return f;    int s=0,t;    for(int k=last[x];k;k=a[k].next) {        int y=a[k].y;        if(h[y]==h[x]+1&&a[k].c>0&&s<f) {            t=findflow(y,min(a[k].c,f-s));            s+=t;a[k].c-=t;a[a[k].other].c+=t;        }    }    if(s==0)        h[x]=0;    return s;}int main() {    int n,m;scanf("%d%d",&n,&m);    len=0;memset(last,0,sizeof(last));    for(int i=1;i<=n;i++)  //横着连边        for(int j=1;j<m;j++) {            int c;scanf("%d",&c);            ins((i-1)*m+j,(i-1)*m+j+1,c);        }    for(int i=1;i<n;i++)   //竖着连边        for(int j=1;j<=m;j++) {            int c;scanf("%d",&c);            ins((i-1)*m+j,i*m+j,c);        }    for(int i=1;i<n;i++) //斜着连边,自己yy吧。        for(int j=1;j<m;j++) {            int c;scanf("%d",&c);            ins((i-1)*m+j,i*m+j+1,c);        }    st=1;ed=n*m;    int ans=0;    while(bfs()==true)        ans+=findflow(st,999999999);    printf("%d\n",ans);    return 0;}

网络流就要看清本质。
流的是什么。怎么构图。
网络流还是很D的。

原创粉丝点击