若当前搜索到的城市n前面1~n-1编号的城市中有没有通电的,则永远也无法输送电力给那个城市,因为在剪枝时附加了和此结点连接的最大结点小于当前的结点
这段
for(int i = 1; i < cur; i++)
if(!vis[i] && map[i][0] < cur)
return;
#include<iostream> #include <new> #include<stdio.h> #include<memory.h> using namespace std; int n, m; int map[100][100]; int index2[100]; int vis[100]; int res = 0; void sort(int a[], int length) { for(int i = 0; i < length; i++) for(int j = 1; j < length - i; j++) if(a[j] > a[j - 1]) { int k = a[j - 1]; a[j - 1] = a[j]; a[j] = k; } } void dfs(int cur, int sum, int total) { if(sum >= res) return; if(total == n) { res = sum; return; } for(int i = 1; i < cur; i++) if(!vis[i] && map[i][0] < cur) return; //不选 dfs(cur + 1, sum, total); int k = 0; int vis2[100] = { 0 }; for(int i = 0; i < index2[cur]; i++) { if(!vis[map[cur][i]]) { vis[map[cur][i]] = 1; //选,这次覆盖到点 vis2[k++] = map[cur][i]; } } if(!k) //没有新的点覆盖 return; dfs(cur + 1, sum + 1, total + k); for(int i = 0; i < k; i++) vis[vis2[i]] = 0; } int main() { freopen("d:\\1.txt", "r", stdin); while (cin >> n >> m && n != 0 && m != 0) { memset(map, -1, sizeof(map)); memset(vis, 0, sizeof(vis)); memset(index2, 0, sizeof(index2)); int s, e; for(int i = 0; i < m; i++) { cin >> s >> e; map[s][index2[s]++] = e; map[e][index2[e]++] = s; } for(int i = 1; i <= n; i++) { map[i][index2[i]++] = i; sort(map[i], index2[i]); } res = 0x7fffffff; dfs(1, 0, 0); cout << res << endl; } return 0; }