标签:
比较裸的流了。。显然是最小割,S连狼=inf,羊连T=inf,狼羊和空地间=1,然后跑就行了,dinic略慢。。
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include<ctime> 5 #include<cmath> 6 #include<iostream> 7 #include<algorithm> 8 #include<queue> 9 #include<stack> 10 #include<set> 11 #define clr(a,x) memset(a,x,sizeof(a)) 12 #define rep(i,l,r) for(int i=(l);i<(r);i++) 13 using namespace std; 14 typedef long long ll; 15 typedef pair<int,int> pii; 16 #define mkp(a,b) make_pair(a,b) 17 int read(){ 18 int ans=0,f=1; 19 char c=getchar(); 20 while(!isdigit(c)){ 21 if(c==‘-‘) f=-1; 22 c=getchar(); 23 } 24 while(isdigit(c)){ 25 ans=ans*10+c-‘0‘; 26 c=getchar(); 27 } 28 return ans*f; 29 } 30 const int maxn=109,inf=0x3fffffff; 31 int S,T,n,m,a[maxn][maxn],d[maxn*maxn]; 32 #define cnt(a,b) (((a)-1)*m+(b)) 33 struct edge{ 34 int v,w; 35 edge*next,*r; 36 }e[maxn*maxn<<3],*fir[maxn*maxn],*cur[maxn*maxn],*pt=e; 37 void add(int u,int v,int w){ 38 pt->v=v;pt->w=w; 39 pt->next=fir[u]; 40 fir[u]=pt++; 41 } 42 void addedge(int u,int v,int w){ 43 add(u,v,w);add(v,u,0); 44 fir[u]->r=fir[v];fir[v]->r=fir[u]; 45 } 46 bool bfs(){ 47 queue<int>Q;Q.push(S); 48 clr(d,0);d[S]=1; 49 while(!Q.empty()){ 50 int x=Q.front();Q.pop(); 51 for(edge*e=fir[x];e;e=e->next){ 52 if(e->w&&!d[e->v]){ 53 d[e->v]=d[x]+1;Q.push(e->v); 54 } 55 } 56 } 57 return d[T]; 58 } 59 int dfs(int x,int w){ 60 if(x==T||!w) return w; 61 int f=0; 62 for(edge*&e=cur[x];e;e=e->next){ 63 if(e->w&&d[e->v]==d[x]+1){ 64 int g=dfs(e->v,min(e->w,w)); 65 if(g>0){ 66 f+=g; 67 e->w-=g; 68 e->r->w+=g; 69 if(!(w-=g)) break; 70 } 71 } 72 } 73 return f; 74 } 75 int maxflow(){ 76 int ans=0; 77 while(bfs()){ 78 rep(i,S,T+1) cur[i]=fir[i]; 79 ans+=dfs(S,inf); 80 } 81 return ans; 82 } 83 int main(){ 84 n=read();m=read();S=0;T=n*m+1; 85 rep(i,1,n+1) 86 rep(j,1,m+1) a[i][j]=read(); 87 rep(i,1,n+1) 88 rep(j,1,m+1){ 89 if(a[i][j]==1) addedge(S,cnt(i,j),inf); 90 if(a[i][j]==2) addedge(cnt(i,j),T,inf); 91 if(i-1>0&&(a[i-1][j]!=a[i][j]||!(a[i-1][j]|a[i][j]))) addedge(cnt(i-1,j),cnt(i,j),1); 92 if(i+1<=n&&(a[i+1][j]!=a[i][j]||!(a[i+1][j]|a[i][j]))) addedge(cnt(i+1,j),cnt(i,j),1); 93 if(j-1>0&&(a[i][j-1]!=a[i][j]||!(a[i][j-1]|a[i][j]))) addedge(cnt(i,j-1),cnt(i,j),1); 94 if(j+1<=m&&(a[i][j+1]!=a[i][j]||!(a[i][j+1]|a[i][j]))) addedge(cnt(i,j+1),cnt(i,j),1); 95 } 96 printf("%d\n",maxflow()); 97 return 0; 98 }
标签:
原文地址:http://www.cnblogs.com/chensiang/p/4999154.html