题意:
给一个图染色,相邻的点不能染相同的颜色,问最少需要多少种颜色。
思路:
搜索。
注意:在给一个新点染色的时候,用过的颜色中可以用的要试一下,没用过的颜色也要试一下,才不会出错。
数据:
10 A:BCDEFG B:ACGH C:ABDH D:ACEHJ E:ADFIJ F:AEGI G:ABFHI H:BCDGIJ I:EFGHJ J:DEHI 4 channels needed.
6 A:BEF B:AC C:BD D:CEF E:ADF F:ADE 3 channels needed.
实现:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 6 using namespace std; 7 8 const int MAXN = 30, INF = 0x3f3f3f3f; 9 10 int G[MAXN][MAXN], color[MAXN], n, ans; 11 string s; 12 13 void dfs(int now, int c) 14 { 15 if (now == n) 16 { 17 ans = min(ans, c); 18 return; 19 } 20 int * buf = new int[MAXN]; 21 for (int i = 0; i < MAXN; i++) buf[i] = 0; 22 int maxn = 0; 23 for (int i = 0; i < now; i++) 24 { 25 if (G[now][i] && color[i]) 26 { 27 maxn = max(maxn, color[i]); 28 buf[color[i]] = 1; 29 } 30 } 31 for (int i = 1; i <= maxn + 1; i++) 32 { 33 if (!buf[i]) 34 { 35 color[now] = i; 36 dfs(now + 1, max(i, c)); 37 } 38 } 39 delete buf; 40 } 41 42 int main() 43 { 44 while (cin >> n, n) 45 { 46 memset(G, 0, sizeof(G)); 47 memset(color, 0, sizeof(color)); 48 ans = INF; 49 for (int i = 0; i < n; i++) 50 { 51 cin >> s; 52 int l = s.length(); 53 for (int j = 2; j < l; j++) 54 { 55 int tmp = s[j] - 'A'; 56 G[i][tmp] = G[tmp][i] = 1; 57 } 58 } 59 dfs(0, 0); 60 cout << ans << " channel" << (ans > 1 ? "s" : "") << " needed." << endl; 61 } 62 return 0; 63 }