# bzoj1412: [ZJOI2009]狼和羊的故事

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
const int dx[4]={-1,0,1,0};
const int dy[4]={0,1,0,-1};

struct node
{
int x,y,c,next,other;
}a[210000];int len,last[11000];
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 n,m,st,ed;

int h[11000],list[11000];
bool bt_h()
{
memset(h,0,sizeof(h));h[st]=1;
{
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;
tail++;
}
}
}
if(h[ed]==0)return false;
return true;
}
int findflow(int x,int f)
{
if(x==ed)return f;
int s=0;
for(int k=last[x];k;k=a[k].next)
{
int y=a[k].y;
if(a[k].c>0&&h[x]+1==h[y]&&s<f)
{
int 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 mp[110][110];
int point(int x,int y){return (x-1)*m+y;}
int main()
{
scanf("%d%d",&n,&m);
st=n*m+1;ed=n*m+2;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&mp[i][j]);

len=0;memset(last,0,sizeof(last));
for(int x=1;x<=n;x++)
{
for(int y=1;y<=m;y++)
{
int p=point(x,y);
if(mp[x][y]==1)ins(st,p,999999999);
else if(mp[x][y]==2)ins(p,ed,999999999);

if(mp[x][y]==1)
{
for(int i=0;i<=3;i++)
{
int tx=x+dx[i],ty=y+dy[i];
if(tx>0&&tx<=n&&ty>0&&ty<=m&&mp[x][y]!=mp[tx][ty])
ins(p,point(tx,ty),1);
}
}
else if(mp[x][y]==0)
{
for(int i=0;i<=3;i++)
{
int tx=x+dx[i],ty=y+dy[i];
if(tx>0&&tx<=n&&ty>0&&ty<=m&&mp[tx][ty]!=1)
ins(p,point(tx,ty),1);
}
}
}
}

//------composition------------

int ans=0;
while(bt_h()==true)
{
ans+=findflow(st,999999999);
}
printf("%d\n",ans);
return 0;
}

pain and happy in the cruel world.
posted @ 2018-01-30 21:20  AKCqhzdy  阅读(118)  评论(0编辑  收藏  举报