hdu4185

重新建图+二分图匹配

#include
using namespace std;
const int maxn = 600 + 10;
vectorg[maxn];
int from[maxn],ans,n;
bool use[maxn];
int mp[maxn][maxn];
bool match(int x){
	int len = g[x].size();
	for (int i = 0; i < len; ++i)
	if (!use[g[x][i]]){
		use[g[x][i]] = true;
		if (from[g[x][i]] == -1 || match(from[g[x][i]])){
			from[g[x][i]] = x;
			return true;
		}
	}
	return false;
}
int hungary(){
	ans = 0;
	memset(from, 255 ,sizeof(from));
	for (int i = 1; i <= n; ++i){
		memset(use,0,sizeof(use));
		if (match(i))++ans;
	}
	return ans;
}
int main(){
	int T,cnt=0,m;
	memset(mp,0,sizeof(mp));
	scanf("%d",&T);
	while(T--){
		for (int i = 0; i < maxn; ++i)g[i].clear();
		n=0;
		scanf("%d",&m);
		for (int i = 1; i <= m; ++i){
			getchar();
			for (int j = 1; j <= m; ++j){
				if (getchar() == '#')mp[i][j] = ++n;
				else mp[i][j] = 0;
			}
		}
		for (int i = 1; i <= m; ++i){
			for (int j = 1; j <= m; ++j)if (mp[i][j]){
				int u = mp[i][j];
				if (mp[i-1][j])g[u].push_back(mp[i-1][j]);		
				if (mp[i+1][j])g[u].push_back(mp[i+1][j]);
				if (mp[i][j-1])g[u].push_back(mp[i][j-1]);
				if (mp[i][j+1])g[u].push_back(mp[i][j+1]);
			}
		}
		hungary();
		printf("Case %d: %d\n",++cnt,ans/2);
	}
	return 0;
}

 

你可能感兴趣的:(hdu4185)