题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3046
思路:最小割的入门题,设源点为0,汇点为n*m+1,源点与点为2的连一天容量为inf的边,汇点与点为1的连容量为inf的边,每个相邻网格连容量为1的边。
View Code
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 #define MAXN 44444 6 #define MAXM 555555 7 #define inf 1<<30 8 struct Edge{ 9 int v,cap,next; 10 }edge[MAXM]; 11 12 int head[MAXN]; 13 int pre[MAXN]; 14 int cur[MAXN]; 15 int level[MAXN]; 16 int gap[MAXN]; 17 int NV,NE,n,m,vs,vt; 18 int dir[4][2]={{0,-1},{0,1},{-1,0},{1,0}};//up,down,left,right 19 20 void Insert(int u,int v,int cap,int cc=0){ 21 edge[NE].v=v;edge[NE].cap=cap; 22 edge[NE].next=head[u];head[u]=NE++; 23 24 edge[NE].v=u;edge[NE].cap=cc; 25 edge[NE].next=head[v];head[v]=NE++; 26 } 27 28 29 int SAP(int vs,int vt){ 30 memset(pre,-1,sizeof(pre)); 31 memset(level,0,sizeof(level)); 32 memset(gap,0,sizeof(gap)); 33 for(int i=0;i<=n*m+1;i++)cur[i]=head[i]; 34 int u=pre[vs]=vs,maxflow=0,aug=-1; 35 gap[0]=NV; 36 while(level[vs]<NV){ 37 loop: 38 for(int &i=cur[u];i!=-1;i=edge[i].next){ 39 int v=edge[i].v; 40 if(edge[i].cap&&level[u]==level[v]+1){ 41 aug==-1?aug=edge[i].cap:(aug=min(aug,edge[i].cap)); 42 pre[v]=u; 43 u=v; 44 if(v==vt){ 45 maxflow+=aug; 46 for(u=pre[u];v!=vs;v=u,u=pre[u]){ 47 edge[cur[u]].cap-=aug; 48 edge[cur[u]^1].cap+=aug; 49 } 50 aug=-1; 51 } 52 goto loop; 53 } 54 } 55 int minlevel=NV; 56 for(int i=head[u];i!=-1;i=edge[i].next){ 57 int v=edge[i].v; 58 if(edge[i].cap&&minlevel>level[v]){ 59 cur[u]=i; 60 minlevel=level[v]; 61 } 62 } 63 gap[level[u]]--; 64 if(gap[level[u]]==0)break; 65 level[u]=minlevel+1; 66 gap[level[u]]++; 67 u=pre[u]; 68 } 69 return maxflow; 70 } 71 72 73 int main(){ 74 int _case=1,tmp; 75 while(~scanf("%d%d",&n,&m)){ 76 NE=0,NV=n*m+2,vs=0,vt=n*m+1; 77 memset(head,-1,sizeof(head)); 78 for(int i=1;i<=n;i++){ 79 for(int j=1;j<=m;j++){ 80 scanf("%d",&tmp); 81 if(tmp==1){Insert((i-1)*m+j,vt,inf);} 82 else if(tmp==2){Insert(vs,(i-1)*m+j,inf);} 83 for(int k=0;k<4;k++){ 84 int x=i+dir[k][0]; 85 int y=j+dir[k][1]; 86 if(x>=1&&x<=n&&y>=1&&y<=m){Insert((i-1)*m+j,(x-1)*m+y,1);} 87 } 88 } 89 } 90 printf("Case %d:\n",_case++); 91 printf("%d\n",SAP(vs,vt)); 92 } 93 return 0; 94 }