题解:最小割等于最大流。
所有的狼向源点连一条容量为INF 的边,所有的羊向汇点连一条容量为INF的边,然后矩阵中的每个节点向他相邻的节点连边,容量为一,注意因为矩阵中走时没有方向所以一条边要正反加两次。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> #define N 200003 #define inf 1000000000 using namespace std; int n,m; int next[N],point[N],v[N],remain[N],a[103][103]; int deep[N],cur[N],num[N],tot,laste[N]; void add(int x,int y,int z) { tot++; next[tot]=point[x]; point[x]=tot; v[tot]=y; remain[tot]=z; tot++; next[tot]=point[y]; point[y]=tot; v[tot]=x; remain[tot]=0; } int addflow(int s,int t) { int now=t; int ans=inf; while (now!=s) { ans=min(ans,remain[laste[now]]); now=v[laste[now]^1]; } now=t; while (now!=s) { remain[laste[now]]-=ans; remain[laste[now]^1]+=ans; now=v[laste[now]^1]; } return ans; } void bfs(int s,int t) { for (int i=s;i<=t;i++) deep[i]=t; deep[t]=0; queue<int> p; p.push(t); while (!p.empty()) { int now=p.front(); p.pop(); for (int i=point[now];i!=-1;i=next[i]) if (deep[v[i]]==t&&remain[i^1]) { deep[v[i]]=deep[now]+1; p.push(v[i]); } } } int isap(int s,int t) { bfs(s,t); int ans=0; for (int i=s;i<=t;i++) cur[i]=point[i]; for (int i=s;i<=t;i++) num[deep[i]]++; int now=s; while (deep[s]<t) { if (now==t) { ans+=addflow(s,t); now=s; } bool f=false; for (int i=cur[now];i!=-1;i=next[i]) if (deep[v[i]]+1==deep[now]&&remain[i]) { f=true; laste[v[i]]=i; cur[now]=i; now=v[i]; break; } if (!f) { int minn=t; for (int i=point[now];i!=-1;i=next[i]) if (remain[i]) minn=min(deep[v[i]],minn); if (!--num[deep[now]]) break; deep[now]=minn+1; num[deep[now]]++; cur[now]=point[now]; if (now!=s) now=v[laste[now]^1]; } } return ans; } int main() { freopen("a.in","r",stdin); freopen("my.out","w",stdout); scanf("%d%d",&n,&m); int num=n*m+2; memset(next,-1,sizeof(next)); memset(point,-1,sizeof(point)); tot=-1; for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) { int x; scanf("%d",&x); int t=(i-1)*m+j+1; if (x==2) add(1,t,inf); if (x==1) add(t,num,inf); if (j!=m) add(t,(i-1)*m+j+2,1),add(t+1,t,1); if (i!=n) add(t,i*m+j+1,1),add(i*m+j+1,t,1); } int t=isap(1,num); printf("%d\n",t); }