Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 16 Accepted Submission(s): 12
#include<bits/stdc++.h> using namespace std; const int inf=0x3f3f3f3f; const int N=40010,M=1000010; int T,n,m,a,b,h[N],s,t,base; char g[110][110]; int head[N],nex[M],w[M],to[M],tot; inline void ade(int a,int b,int c) { to[++tot]=b; nex[tot]=head[a]; w[tot]=c; head[a]=tot; } inline void add(int a,int b,int c) { ade(a,b,c); ade(b,a,0); } inline int id(int x,int y){return m*x+y;} inline int bfs() { memset(h,0,sizeof h); h[s]=1; queue<int> q; q.push(s); while(q.size()) { int u=q.front(); q.pop(); for(int i=head[u];i;i=nex[i]) { if(!h[to[i]]&&w[i]) { h[to[i]]=h[u]+1; q.push(to[i]); } } } return h[t]; } int dfs(int x,int f) { if(x==t) return f; int fl=0; for(int i=head[x];i&&f;i=nex[i]) { if(h[to[i]]==h[x]+1&&w[i]) { int mi=dfs(to[i],min(w[i],f)); w[i]-=mi; w[i^1]+=mi; fl+=mi; f-=mi; } } if(!fl) h[x]=-1; return fl; } int dinic() { int res=0; while(bfs()) res+=dfs(s,inf); return res; } signed main() { cin>>T; while(T--) { tot=1; memset(head,0,sizeof head); cin>>n>>m>>a>>b; base=(n+2)*m; t=base*2; for(int i=1;i<=n;i++) scanf("%s",g[i]+1); for(int i=1;i<=a;i++) { int x; scanf("%d",&x); g[0][x]=‘1‘; add(s,id(0,x),1); add(id(0,x),id(1,x),1); } for(int i=1;i<=b;i++) { int x; scanf("%d",&x); g[n+1][x]=‘1‘; add(id(n+1,x),t,inf); add(id(n,x),id(n+1,x),inf); } for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(g[i][j]==‘1‘) continue; if(i>1) add(id(i,j),id(i-1,j),1); if(i<n) add(id(i,j),id(i+1,j),1); if(j>1) add(id(i,j)+base,id(i,j-1)+base,1); if(j<m) add(id(i,j)+base,id(i,j+1)+base,1); add(id(i,j),id(i,j)+base,1);add(id(i,j)+base,id(i,j),1); } } puts(dinic()==a?"Yes":"No"); } return 0; }
原文:https://www.cnblogs.com/songorz/p/11604737.html