题目大意:有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;
}