这道题最难的部分就是建图,能想到怎么建图,就没有问题了,直接套模板即可。
建图:将每个‘#’的格子作为一个节点,和与它相邻的格子连线,构建一个图,求这个图的最大二分匹配!要注意的是,这个图的最大二分匹配,是把所有的‘#’既做为左边,有作为右边,因此,匹配出来的是答案的二倍。即一个点被匹配了两次,因为在建图的过程中,比如(1,2)这条边,它还有对应的(2,1)这条边,仔细看看建图,画一下就懂了!
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 660;
int T, n, bimap[N][N], id[N][N], cnt;
int cy[N], cx[N];
bool used[N];
char g[N][N];
bool dfs( int u )
{
for ( int v = 1; v < cnt; ++v ) if ( bimap[u][v] && !used[v] ) {
used[v] = 1;
if ( cy[v] == -1 || dfs( cy[v] )) {
cy[v] = u;
return 1;
}
}
return 0;
}
int match( )
{
int res = 0;
memset( cy, -1, sizeof(cy));
memset( cx, -1, sizeof(cx));
for ( int i = 1; i < cnt; ++i ) {
memset( used, 0, sizeof(used));
if ( dfs(i) ) res++;
}
return res;
}
int main()
{
scanf("%d", &T);
int icase = 1;
while ( T-- ) {
scanf("%d", &n);
cnt = 1;
getchar();
memset( bimap, 0, sizeof(bimap));
memset( id, 0, sizeof(id));
for ( int i = 0; i < n; ++i, getchar() ) {
for ( int j = 0; j < n; ++j ) {
scanf("%c", &g[i][j]);
if ( g[i][j] == '#' ) id[i][j] = cnt++;
}
}
//for ( int i = 0; i < n; ++i, printf("\n") ) for ( int j = 0; j < n; ++j ) printf("%c", g[i][j]);
for ( int i = 0; i < n; ++i ) {
for ( int j = 0; j < n; ++j ) {
if ( g[i][j] != '#' ) continue;
if ( i > 0 && g[i-1][j] == '#' ) bimap[id[i][j]][id[i-1][j]] = 1;
if ( j > 0 && g[i][j-1] == '#' ) bimap[id[i][j]][id[i][j-1]] = 1;
if ( i < n-1 && g[i+1][j] == '#' ) bimap[id[i][j]][id[i+1][j]] = 1;
if ( j < n-1 && g[i][j+1] == '#' ) bimap[id[i][j]][id[i][j+1]] = 1;
}
}
printf("Case %d: %d\n", icase++, match()/2);
}
}