一、题目

​屠龙宝刀点击就送​

二、思路

相邻的两个中继器不能使用相同的频道。不相邻的中继器可以使用相同的频道并尽量使用现有频道,这样才能保证使用的频道数量最少。

不同的频道可以用不同的颜色来表示,则样例中的三个网络如下图所示:

OpenJudge 131《Channel Allocation》题解报告_ios


网络1中,中继器A和中继器B不相邻,使用一个频道(即同色)就够。。

网络2中,中继器D与中继器A不相邻,则D的频道(颜色)要与A的一样,这样才能保证使用的频道总数量最少。

三、代码

#include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;

bool adj[30][30];
int col[30]; //col[i]表示节点i的颜色
int n, minColor;//minColor为最少的颜色数量
bool allDyed; //为true表示所有节点都已染色

bool canDye(int x, int color)//判断节点x是否能染c颜色
{
for(int i = 1; i <= n; i++)
{
//x不能与相邻节点同色
if(adj[x][i] == true && col[i] == color)
{
return false;
}
}

return true;
}

//节点x先在total种颜色里选颜色,若没法选则添加一种新颜色
//x=1时是A节点,x=2时是B节点,x=3时是C节点,……
void dfs(int x, int total)
{
if(x > n)
{
allDyed = true; //flag为true时表示所有节点都已染色
minColor = total;
return;
}

//枚举看看节点是否可以染1~color之间的某种颜色
for(int c = 1; c <= total; c++)
{
if(canDye(x, c))
{
col[x] = c;
dfs(x + 1, total);
if(allDyed == true)
{
return;
}
}
}

col[x] = total + 1;//节点x需要染一种新的颜色
dfs(x + 1, total + 1);//颜色总数量多了1种
}

int main()
{
//freopen("channel.in","r",stdin);

while(cin >> n && n)
{
allDyed = false;
memset(adj, false, sizeof(adj));
memset(col, 0, sizeof(col));

for(int i = 0; i < n; i++)
{
string s;
cin >> s;
int len = s.size();
int x = s[0] - 'A' + 1;//A对应1,B对应2,……,Z对应26
for(int i = 2; i < len; i++)
{
int y = s[i] - 'A' + 1;
adj[x][y] = true; //节点x与节点y相邻
adj[y][x] = true;
}
}

dfs(1, 1);

cout << minColor;
if(1 == minColor)
{
cout << " channel needed." << endl;
}
else
{
cout << " channels needed." << endl;
}
}

return 0;
}