BZOJ1412: [ZJOI2009]狼和羊的故事

【传送门:BZOJ1412


简要题意:

  给出一个矩阵,0表示空地,1表示狼,2表示羊,要求在格子之间装栅栏使得狼和羊不在一个块里

  求出最少的栅栏


题解:

  最小割

  st连向狼,流量为无限,羊连向ed,流量为无限

  每只狼和空地连向相邻的空地和羊,流量为1

  然后跑最大流就好了


参考代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
using namespace std;
struct node
{
    int x,y,c,next,other;
}a[210000];int len,last[11000];
void ins(int x,int y,int c)
{
    int k1=++len,k2=++len;
    a[k1].x=x;a[k1].y=y;a[k1].c=c;
    a[k1].next=last[x];last[x]=k1;
    a[k2].x=y;a[k2].y=x;a[k2].c=0;
    a[k2].next=last[y];last[y]=k2;
    a[k1].other=k2;
    a[k2].other=k1;
}
int h[11000],list[11000],st,ed;
bool bt_h()
{
    memset(h,0,sizeof(h));
    h[st]=1;
    int 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;
            }
        }
        head++;
    }
    if(h[ed]==0) return false;
    else 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&&f>s)
        {
            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 dx[5]={0,0,0,1,-1};
int dy[5]={0,1,-1,0,0};
int s[110][110];
int n,m;
int p(int i,int j)
{
    return (i-1)*m+j;
}
int main()
{
    scanf("%d%d",&n,&m);
    st=0;ed=n*m+1;
    len=0;memset(last,0,sizeof(last));
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            scanf("%d",&s[i][j]);
            if(s[i][j]==1) ins(st,p(i,j),999999999);
            if(s[i][j]==2) ins(p(i,j),ed,999999999);
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(s[i][j]==0||s[i][j]==1)
            {
                for(int k=1;k<=4;k++)
                {
                    int tx=i+dx[k],ty=j+dy[k];
                    if(tx<1||ty<1||tx>n||ty>m) continue;
                    if(s[tx][ty]==0||s[tx][ty]==2) ins(p(i,j),p(tx,ty),1);
                }
            }
        }
    }
    int ans=0;
    while(bt_h()==true) ans+=findflow(st,999999999);
    printf("%d\n",ans);
    return 0;
}

 

posted @ 2018-03-26 21:31  Star_Feel  阅读(145)  评论(0编辑  收藏  举报