原题:http://acm.hdu.edu.cn/showproblem.php?pid=4185
题意:
问“##”相邻的两个#,最多有几对;
思路:
把每个#按顺序标号,二分图的X、Y集就是#的标号数;
如果有相邻的#,就将其相连;
最后求最大匹配数,因为相邻的#有重复,所以最后的答案是sum/2;
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 610;
int cas, T = 0;
int n;
char str[maxn];
int map[maxn][maxn], match[maxn*maxn];
bool used[maxn*maxn];
int f[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1};
vector<int>G[maxn*maxn];
bool find(int x)
{
for(int i = 0;i<G[x].size();i++)
{
int k = G[x][i];
if(!used[k])
{
used[k] = true;
if(match[k] == 0 || find(match[k]))
{
match[k] = x;
return true;
}
}
}
return false;
}
int main()
{
scanf("%d", &cas);
while(cas--)
{
scanf("%d", &n);
memset(map, 0, sizeof map);
memset(match, 0, sizeof match);
int cnt = 0;
for(int i = 1;i<=n;i++)
{
scanf("%s", str);
for(int j = 0;j<strlen(str);j++)
{
if(str[j] == '#')
map[i][j] = ++cnt;
}
}
for(int i = 1;i<=n;i++)
{
for(int j = 0;j<n;j++)
{
if(map[i][j])
{
G[map[i][j]].clear();
for(int t = 0;t<4;t++)
{
int a = i+f[t][0];
int b = j+f[t][1];
if(a<1 || b<0 || a>n || b>=n || !map[a][b]) continue;
G[map[i][j]].push_back(map[a][b]);
}
}
}
}
int sum = 0;
for(int i = 1;i<=cnt;i++)
{
memset(used, false, sizeof used);
if(find(i))
sum++;
}
printf("Case %d: %d\n", ++T, sum/2);
}
return 0;
}