题解:
每两个联通的油井建边
然后二分图最大匹配
最后答案除以2
代码:
#include<cstdio> #include<cmath> #include<cstring> #include<algorithm> using namespace std; const int N=20005; char c; int T,a[N/20][N/20],f[N],match[N],fi[N],cas,num,ne[N],zz[N],n,cnt; int dfs(int x) { for (int i=fi[x];i;i=ne[i]) if (!f[zz[i]]) { f[zz[i]]=1; if (!match[zz[i]]||dfs(match[zz[i]])) { match[zz[i]]=x; return 1; } } return 0; } void jb(int x,int y) { ne[++num]=fi[x]; fi[x]=num; zz[num]=y; ne[++num]=fi[y]; fi[y]=num; zz[num]=x; } int main() { scanf("%d",&T); while (T--) { memset(a,0,sizeof a); memset(fi,0,sizeof fi); num=0; scanf("%d",&n); for (int i=0;i<n;i++) for (int j=0;j<n;j++) { int ch=getchar(); while (ch!='.'&&ch!='#')ch=getchar(); if (ch=='#')a[i][j]=++cnt; else a[i][j]=0; } for (int i=0;i<n;i++) for (int j=0;j<n;j++) if (a[i][j]) { if (a[i+1][j])jb(a[i][j],a[i+1][j]); if (a[i][j+1])jb(a[i][j],a[i][j+1]); } int ans=0; for (int i=1;i<=cnt;i++) { memset(f,0,sizeof f); ans+=dfs(i); } printf("Case %d: %d\n",++cas,ans/2); } return 0; }