来源:http://poj.org/problem?id=1129
题意:给一些电台,相邻的电台之间不能共用一个频道。求最少能用多少个频道让所有的电台都能使用。
思路:其实是个着色问题了。介绍一下着色问题,给一个平面图,相邻的之间不能用同一种颜色,最少需要多少种颜色涂完平面图。着色问题的最原始版本是四色问题。平面图上相邻的图就相当于本题中的相邻的电台,用多少种颜色即为多少个频道。
至于解法,因为本题数据小,最多有26个电台,也就是说最多需要26种颜色。因此可以枚举颜色种类,满足条件时输出即可。判断时用深搜,其实这题就是暴力过的,暴力判断是否满足条件即可。
代码:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <vector>
#include <queue>
#include <string>
using namespace std;
#define CLR(arr,val) memset(arr,val,sizeof(arr))
const int N = 30;
int color[N],num;
vector<int> vv[N];
bool isok(int x){
for(int i = 0; i < vv[x].size(); ++i){
int y = vv[x][i];
if(color[x] == color[y]) return false;
}
return true;
}
bool dfs(int cnt,int numcolor){
if(cnt > num) return true;
else{
for(int i = 1; i <= numcolor; ++i){
color[cnt] = i;
if(isok(cnt)){
if(dfs(cnt+1,numcolor))
return true;
}
color[cnt] = 0;
}
}
return false;
}
int main(){
//freopen("1.txt","r",stdin);
while(scanf("%d",&num) &&num){
CLR(color,0);
string ss;
for(int i = 1;i <= num; ++i)
vv[i].clear();
for(int i = 1; i <= num; ++i){
cin >> ss;
// printf("ss = %d\n",ss.size());
if(ss.size() <= 2)
continue;
int x = (int)(ss[0] - 'A' + 1);
for(int j = 2; j < ss.size(); ++j){
int y = (int)(ss[j] - 'A' + 1);
vv[x].push_back(y);
}
}
for(int i = 1; i <= num; ++i){
if(dfs(1,i)){
if(i == 1){
printf("1 channel needed.\n");
}
else
printf("%d channels needed.\n",i);
break;
}
}
}
return 0;
}