题意:有无向图,相邻两个点上的颜色不同,问若途中每个点都要上色,最少的上色颜色种类。
想法:因为最多只有26个点,因此,假设当前使用k种颜色,然后将k个颜色往上面去涂抹,如果满足题目中的要求就输出k即可,如果有矛盾产生,那么久将颜色种类提升到k + 1种颜色,再去判断。
#include<stdio.h> #include<string.h> int n; int map[27][27]; int col[27]; int max_col; bool Judge(int index, int c) { for(int i = 1; i <= n; ++i){ if(map[index][i] && col[i] == c){ return false; } } return true; } bool DFS(int cur_index, int color) { if(cur_index > n){ max_col = color; return true; } for(int i = 1; i <= color; ++i){ if(Judge(cur_index, i)){ col[cur_index] = i; if(DFS(cur_index + 1, color)) return true; col[cur_index] = 0; } } if(col[cur_index] == 0){ if(DFS(cur_index, color + 1)) return true; } return false; } int main() { while(~scanf("%d",&n) && n){ memset(map, 0, sizeof(map)); memset(col, 0,sizeof(col)); for(int i = 1; i <= n; i++){ char in_char[30]; int length; scanf("%s",in_char); length = strlen(in_char); for(int i = 2; i <= length - 1; i++){ map[in_char[0] - 'A' + 1][in_char[i] - 'A' + 1] = 1; } } DFS(1, 1); if(max_col == 1) printf("1 channel needed.\n"); else printf("%d channels needed.\n",max_col); } return 0; }