HDU 4185 — Oil Skimming 二分匹配

原題: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;
}


發佈了99 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章