先建图,然后对一个顶点点先染色,如果它的邻点颜色不同,搜索下一个顶点,如果颜色不够,颜色增加
由于顶点少,就不用四色原理剪枝了
Source Code
Problem: 1129 User: fisty
Memory: 656K Time: 0MS
Language: G++ Result: Accepted
Source Code
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAX_N 26
int n, ans, color[MAX_N];
bool map[MAX_N][MAX_N],isfind;
bool ok (int x, int c){
for(int i = 0;i < n; i++)
if(map[x][i] && c == color[i])
return false;
return true;
}
void DFS(int id, int total){
if(isfind) return ;
if(id>=n) {isfind = true;return ;}
for(int i = 1;i <= total; i++){
if(ok(id, i)){
color[id] = i;
DFS(id+1, total);
color[id] = 0;
}
}
if(!isfind){
ans++;
DFS(id, total+1);
}
}
int main(){
char s[MAX_N];
while(scanf("%d", &n) && n){
getchar();
memset(map, false, sizeof(map));
memset(color, 0, sizeof(color));
for(int i = 0;i < n; i++){
gets(s);
for(int j = 2;s[j] != '\0'; j++){
map[s[0] - 'A'][s[j] - 'A'] = true;
map[s[j] - 'A'][s[0] - 'A'] = true;
}
}
isfind = false;
ans = 1;
DFS(0, 1);
if(ans == 1)
printf("1 channel needed.\n");
else
printf("%d channels needed.\n",ans);
}
return 0;
}