[BZOJ1412][ZJOI2009]狼和羊的故事(最小割)

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1412


一道很经典的最小割,很有参考价值
这题要把狼和羊分开,同时要求最短,那么很明显是最小割了。。。
建图方法为:
st->狼(值为INF,这样就可以保证狼和羊在两个集合里面)
狼->相邻的羊和空地(值为1,可以感性的把它看作栅栏)
空地->相邻的羊和空地(值为1,同理)
羊->ed(值为INF,同st到狼)


code:

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int dx[]={-1,0,1,0};
const int dy[]={0,1,0,-1};
const int INF=99999999;
struct node
{
    int x,y,c,next,other;
}a[2110000]; int len,last[1110000];
int st,ed;
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=0;
    a[len].next=last[y]; last[y]=len;
    a[k1].other=k2;
    a[k2].other=k1;
}
int list[1110000],head,tail,h[1110000];
bool bt()
{
    memset(h,0,sizeof(h)); h[st]=1;
    list[1]=st;
    head=1,tail=2;
    while(head!=tail)
    {
        int x=list[head];
        for(int k=last[x];k;k=a[k].next)
        {
            int y=a[k].y;
            if(a[k].c>0 && h[y]==0)
            {
                h[y]=h[x]+1;
                list[tail++]=y;
            }
        }
        head++;
    }
    if(h[ed]>0) return true;
    else return false;
}
int mymin(int x,int y) {return x<y?x:y;}
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(a[k].c>0 && h[y]==h[x]+1 && s<f)
        {
            t=findflow(y,mymin(f-s,a[k].c));
            s+=t; a[k].c-=t; a[a[k].other].c+=t;
        }
    }
    if(s==0) h[x]=0;
    return s;
}
int dinic()
{
    int s=0,t;
    while(bt()==true)
    {
        s+=findflow(st,999999999) ;
    }
    return s;
}
int map[110][110];
//st->狼,狼->相邻的羊和空地,空地->相邻的羊和空地,羊->ed 
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++)
        {
            scanf("%d",&map[i][j]);
        }
    }
    st=n*m+1,ed=st+1;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            int id=(i-1)*m+j;
            if(map[i][j]==1) ins(st,id,INF);
            else if(map[i][j]==2) ins(id,ed,INF);
            for(int k=0;k<4;k++)
            {
                int tx=i+dx[k],ty=j+dy[k];
                if(tx>=1 && tx<=n && ty>=1 && ty<=m && map[i][j]!=2)
                {
                    int id2=(tx-1)*m+ty;
                    if(map[tx][ty]!=1 || map[i][j]!=1)
                        ins(id,id2,1);
                }
            }
        }
    }
    printf("%d\n",dinic());
    return 0;
}       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值