题目大意:给一个网格,1代表?,2代表?,0表示空地,求用最小数量的围墙阻挡?,使其不能伤害?。
最小割。。对每个点和其上下左右的点建立容量为1的边,增加超级源结点和汇结点,跑下最大流。
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int A[300][300],n,m;
int from[500000], p[500000],head[500000],nex[500000],c[500000],e;
int dx[]={0,0,1,-1},dy[]={1,-1,0,0},fa[60000],dp[60000];
queue<int>q;
void add(int u,int v,int w){
p[e]=v;
from[e]=u;
nex[e]=head[u];
head[u]=e;
c[e++]=w;
}
int id(int x,int y){
return (x-1)*(m+1)+y;
}
int mi(int a,int b){
if(a>b) return b;
else return a;
}
int bfs(){
int u,v,i;
memset(dp,33,sizeof(dp));
dp[0]=0;
for(q.push(0);!q.empty();q.pop()){
u=q.front();
for(i=head[u];i;i=nex[i]){
v=p[i];
if(c[i]&&dp[v]>dp[u]+1){
dp[v]=dp[u]+1;
q.push(v);
}
}
}
if(dp[50000]==dp[50001]) return 0;
else return 1;
}
int dfs(int u,int flow){
if(u==50000||flow==0) return flow;
int i,v,sum=0;
for(i=head[u];i;i=nex[i]){
v=p[i];
if(dp[v]==dp[u]+1){
int f=dfs(v,mi(flow-sum,c[i]));
c[i]-=f;
c[i^1]+=f;
sum+=f;
}
if(sum==flow) break;
}
if(sum==0) dp[u]=1e9;
return sum;
}
int main(){
int i,j,k,ca=1;
while(scanf("%d%d",&n,&m)!=EOF){
memset(head,0,sizeof(head));
e=2;
for(i=1;i<=n;i++){
for(j=1;j<=m;j++){
scanf("%d",&A[i][j]);
}
}
for(i=1;i<=n;i++){
for(j=1;j<=m;j++){
for(k=0;k<4;k++){
int x=i+dx[k],y=j+dy[k];
if(x<=n&&y<=m&&x>=1&&y>=1){
add(id(i,j),id(x,y),1);
add(id(x,y),id(i,j),0);
}
}
if(A[i][j]==1){
add(id(i,j),50000,1e9);
add(50000,id(i,j),0);
}
if(A[i][j]==2){
add(0,id(i,j),1e9);
add(id(i,j),0,0);
}
}
}
int ans=0;
while(bfs()) ans+=dfs(0,1e9);
printf("Case %d:\n%d\n",ca++,ans);
}
return 0;
}