D - Hiding Gold(最大匹配数 匈牙利 搜索)

You are given a 2D board where in some cells there are gold. You want to fill the board with 2 x 1 dominoes such that all gold are covered. You may use the dominoes vertically or horizontally and the dominoes may overlap. All you have to do is to cover the gold with least number of dominoes.

In the picture, the golden cells denote that the cells contain gold, and the blue ones denote the 2 x 1 dominoes. The dominoes may overlap, as we already said, as shown in the picture. In reality the dominoes will cover the full 2 x 1 cells; we showed small dominoes just to show how to cover the gold with 11 dominoes.

Input

Input starts with an integer T (≤ 50), denoting the number of test cases.

Each case starts with a row containing two integers m (1 ≤ m ≤ 20) and n (1 ≤ n ≤ 20) and m * n > 1. Here m represents the number of rows, and n represents the number of columns. Then there will be m lines, each containing n characters from the set ['*','o']. A '*' character symbolizes the cells which contains a gold, whereas an 'o' character represents empty cells.

Output

For each case print the case number and the minimum number of dominoes necessary to cover all gold ('*' entries) in the given board.

Sample Input

2

5 8

oo**oooo

*oo*ooo*

******oo

*o*oo*oo

******oo

3 4

**oo

**oo

*oo*

Sample Output

Case 1: 11

Case 2: 4

  • 题意概括  :

给你一个n*m的2D板,一些细胞中存在黄金,而另一些则是空细胞,细胞的大小为1*1,给你一些2*1的多米诺骨牌,问最少需要多少个骨牌能够全部把黄金覆盖。

  • 解题思路  :

首先,搜索记录一共有多少个带有黄金的细胞,然后给每一个细胞编号,相邻的带黄金的细胞进行构图,最后进行二分图匹配,找出最大匹配数,因为图是重复存的所以求出的最大匹配数除以二才是实际的最大匹配数,用细胞黄金数减去最大匹配数最终就是所需多米诺骨牌的数量。

#include<stdio.h>
#include<string.h>

int book[410],girl[410],e[410][410];
int n,m;
char map[410][410];
int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};

int dfs(int u)
{
	int i;
	
	for(i = 0;i<n*m;i ++)
	{
		if(book[i] == 0&&e[u][i] == 1)
		{
			book[i] = 1;
			
			if(girl[i] == 0||dfs(girl[i]))
			{
				girl[i] = u;
				
				return 1;
			}
		}
	}
	return 0;
}

int main()
{
	int i,j,sum,T,t = 0,ans,tx,ty,k;
	
	scanf("%d",&T);
	while(T --)
	{
		scanf("%d %d",&m,&n);
		t ++;
		sum = 0;
		ans = 0;
		memset(e,0,sizeof(e));
		memset(girl,0,sizeof(girl));
		for(i = 0;i<m;i ++)
		{
			scanf("%s",map[i]);
		}
		
		
		for(i = 0;i<m;i ++)
		{
			for(j = 0;j<n;j ++)
			{
				if(map[i][j] == '*')
				{
					sum ++;
					for(k = 0;k<4;k ++)
					{
						tx = i + next[k][0];
						ty = j + next[k][1];
						
						if(tx>=0&&tx<m&&ty>=0&&ty<n)
						{
							if(map[tx][ty] == '*')
							{
								e[i*n+j][tx*n+ty] = 1;
							}
						}
					}
				}
			}
		}
		for(i = 0;i<n*m;i ++)
		{
			memset(book,0,sizeof(book));
			
			if(dfs(i))
			ans ++;
		}
		printf("Case %d: %d\n",t,sum-ans/2);
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值