为每个节点选一个频道,相邻的节点的频道不能相同。
采用深搜,为每个节点选一个编号,从1开始选,因为是从1开始选的,所以选到最后能匹配的一定是最小的频道数。
选一个节点的时候判断一下就OK了。
搜索的题目基本上在POJ上AC完了,UVA上的也A完了。现在对搜索的题目感觉挺有自信的。。呵呵
AC代码:
#include <iostream> #include <cstring> using namespace std; const int MAX_NODES = 28; int nodes; int repeater_number[MAX_NODES]; int maps[MAX_NODES][MAX_NODES]; int channels_number; void dfs(int cur) { if (cur == nodes) return ; else { int flag = 1; for (int i = 1; flag; i++) { int ok = 1; for (int j = 0; j < nodes; j++) { if (maps[cur][j] && repeater_number[j] == i){ ok = 0; break; } } if (ok){ repeater_number[cur] = i; dfs(cur+1); flag = 0; } } } } int main() { while (cin >> nodes) { if (!nodes) break; cin.get(); memset(repeater_number,0,sizeof(repeater_number)); memset(maps,0,sizeof(maps)); for (int i = 0; i < nodes; i++) { char str[MAX_NODES]; cin.getline(str,MAX_NODES); int source_node, target_node; source_node = str[0] - 'A'; for (int j = 2; str[j]; j++) { target_node = str[j] - 'A'; maps[source_node][target_node] = 1; maps[target_node][source_node] = 1; } } channels_number = 0; dfs(0); for (int i = 0; i < nodes; i++) { if(repeater_number[i] > channels_number) channels_number = repeater_number[i]; } if (channels_number > 1) { cout << channels_number << " channels needed." << endl; } else cout << channels_number << " channel needed." << endl; } return 0; }