哈密尔顿回路问题,n比较小,可以用搜索解决.
#include <iostream>
#include <memory.h>
#include <cstdio>
using namespace std;
const int maxn = 11;
int g[maxn][maxn], n;
bool vis[maxn];
bool dfs(int u, int left){
if(left == 0 && u == 0){
return true;
}else if(left == 0)return false;
for(int i = 0; i <= n; ++i){
if(g[u][i] && !vis[i]){
vis[i] = 1;
if(dfs(i, left - 1))return true;
vis[i] = 0;
}
}
return false;
}
int main(){
int cas = 1;
while(scanf("%d\n", &n) && n){
memset(g, 0, sizeof(g));
memset(vis, 0, sizeof(vis));
for(int i = 1; i <= n; ++i){
char ch;
while((ch = getchar()) != '\n'){
if(isdigit(ch)){
cin.putback(ch);
int t;
scanf("%d", &t);
g[t][i] = g[i][t] = 1;
}
}
}
if(dfs(0, n + 1)){
printf("Case %d: Granny can make the circuit.\n",cas++);
}else{
printf("Case %d: Granny can not make the circuit.\n",cas++);
}
}
return 0;
}