D - Channel Allocation POJ - 1129

1129 -- Channel Allocation

题目大意:有n个电台,每个字母代表一个电台,A:B表示A电台与B电台相邻,相邻的电台之间不能用同一个频率,问最少需要多少个频率

1<=n<=26

思路:建立一个有n个节点的有向图,给每个染色,每个相邻点的颜色不能相同,根据四色定理,最多只需要四种颜色,直接dfs遍历图,对于每一个点,查找其相邻的点,遍历当前已用的每种颜色,看相邻点都涂了什么颜色,如果相邻点用到了当前用过的所有颜色,就新建一种颜色,否则把当前点涂成相邻点没用过的颜色统计一共用了多少种颜色

#include<iostream>
#include<string.h>
using namespace std;
int cha[30][30];//图的规模较小,用邻接矩阵存图
int col[30];
int n, ans;
bool temp;
bool check(int cur, int c)
{
	for (int i = 1; i <= n; i++)
	{
		if (cha[cur][i] && c == col[i])
			return 0;//当前选择的颜色与相邻的点颜色相同
	}
	return 1;
}
void dfs(int cur, int tot)//当前点,当前用过的颜色数
{
	if (temp)
		return;
	if (cur > n)//当前搜到的点已经超过点的个数了,开始回溯
	{
		temp = 1;
		return;
	}
	for (int i = 1; i <= tot; i++)
	{//遍历已有的颜色
		if (check(cur, i))
		{//找到了相邻点没有涂的颜色
			col[cur] = i;
			dfs(cur + 1, tot );
		}
	}
	if (!temp)
	{//相邻点涂了当前用过的所有颜色
		ans++;//再新建一种颜色
		col[cur] = ans;
		dfs(cur + 1, tot + 1);
	}
}
int main()
{
	while (cin >> n)
	{
		temp = 0;
		ans = 0;
		if (!n)
			return 0;
		memset(cha, 0, sizeof(cha));
		memset(col, 0, sizeof(col));
		int nn = n;
		for(int j=1;j<=n;j++)
		{
			string s;	
			cin >>s;
			for (int i = 2; i < s.length(); i++)
			{
				cha[j][s[i] - 'A'+1] = 1;
			}//邻接矩阵			
		}
		dfs(1, 0);
		if (ans == 1)
			cout << ans << " channel needed." << endl;
		else
			cout << ans << " channels needed." << endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

timidcatt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值