题目
Channel Allocation - POJ 1129 - Virtual Judge (vjudge.net)
分析
这道题很多博客说用四色定理
但如果所有区域都重叠在一起,即各个基站之间都连一条边时
其需要的频段数便是基站数(下图为AC代码测试的结果)
至于为啥他们四色也能过…
本题思路首先建一个图记录关系,接着从第一个点开始dfs搜索到最后一个点。
因为本身就是无向图,所以我们也没必要管是否跟之前的父节点颜色重合。
直接遍历子节点,若有重合颜色则再将当前要染的颜色加一,最后的颜色便是应该染在该点的颜色。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 27;
bool g[N][N]; // 图图
int color[N]; // 色色
int n, res;
void dfs(int u)
{
if (u == n + 1) // 到头了退出
return;
int i = 1; // 从第一个色开始,尽量从小的开始才是全局最小解
for (i = 1;; i++)
{
bool ok = true;
for (int j = 0; j < n; j++)
if (g[u][j]) // 若有边
{
if (i == color[j])
{
ok = false;
break;
}
}
if (ok) // 如果可以染则退出循环开始染色
break;
}
color[u] = i;
res = max(res, i);
dfs(u + 1);
}
int main()
{
while (cin >> n && n)
{
memset(g, 0, sizeof g);
memset(color, 0, sizeof color);
res = 0;
char s[30];
for (int i = 0; i < n; i++)
{
cin >> s;
for (int j = 2; s[j]; j++)
g[s[0] - 'A'][s[j] - 'A'] = g[s[j] - 'A'][s[0] - 'A'] = true;
}
dfs(0);
cout << res;
if (res > 1)
cout << " channels needed.\n";
else
cout << " channel needed.\n";
}
}