題意:ios
給一個圖染色,相鄰的點不能染相同的顏色,問最少須要多少種顏色。spa
思路:code
搜索。blog
注意:在給一個新點染色的時候,用過的顏色中能夠用的要試一下,沒用過的顏色也要試一下,纔不會出錯。ci
數據:string
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.
實現:it
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 }