poj_3020 Antenna Placement匈牙利算法

思路:

配对的2个点总是一奇一偶,用奇偶点来建二分图,v1是所有奇数点的个数,v2是所有偶数点的个数,假设最大完全匹配了n对,则还剩下没有匹配的v1-n和v2-n个点,这些没有配对的点必须加天线。

所以总数=n+(v1-n)+v2-n)。

一次RE:是因为用char来建了map,char map[45][15],读入int型会越界。

源代码:

#include <iostream>
#include <fstream>

using namespace std;

int h, w;
int map[45][15];
int result;
int v1, v2;
bool bigraph[410][410];
bool visit[410];
int link[410];
int alone;

bool dfs(int x)
{
	for (int y = 1; y <= v2; y++)
	{
		if (bigraph[x][y] && !visit[y])
		{
			visit[y] = true;
			if (link[y] == 0 || dfs(link[y]))
			{
				link[y] = x;
				return true;
			}
		}
	}
	return false;
}

void search()
{
	result = 0;
	memset(link,0,sizeof(link));
	for (int x = 1; x <= v1; x++)
	{
		memset(visit,false,sizeof(visit));
		if (dfs(x))
		{
			result++;
		}
	}
}

int main()
{
	ifstream in("input.txt");
	int cases;
	char temp;
	in >> cases;
	while (cases--)
	{
		in >> h >> w;
		memset(map,0,sizeof(map));
		v1 = v2 = 0;
		for (int i = 1; i <= h; i++)
		{
			for (int j = 1; j <= w; j++)
			{
				in >> temp;
				if (temp == '*')
				{
					if ((i + j) % 2!=0) //奇数点
					{
						map[i][j] = ++v1;
					}
					else //偶数点
					{
						map[i][j] = ++v2;
					}
				}
			}
		}
		memset(bigraph, false, sizeof(bigraph));
		//Construct the bipartite graph
		for (int i = 1; i <= h; i++)
		{
			for (int j = 1; j <= w; j++)
			{
				if (map[i][j] != 0 && (i + j) % 2 != 0)
				{
					if (map[i - 1][j] != 0)
					{
						bigraph[map[i][j]][map[i - 1][j]] = true;
					}
					if (map[i + 1][j] != 0)
					{
						bigraph[map[i][j]][map[i + 1][j]] = true;
					}
					if (map[i][j-1] != 0)
					{
						bigraph[map[i][j]][map[i][j - 1]] = true;
					}
					if (map[i][j+1] != 0)
					{
						bigraph[map[i][j]][map[i][j + 1]] = true;
					}
				}
			}
		}
		//Hungary Algorithm
		search();
		//Result
		result = (v1 - result) + (v2 - result) + result;
		cout << result << endl;
	}
	system("pause");
	return 0;
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值