题目链接:哈密顿绕行世界问题
解析:将每个点的相邻三个点按字典序存放,直接dfs即可。
AC代码:
#include <bits/stdc++.h>
using namespace std;
int city[30][5];
int vis[30];
int pre[30];
int m;
int cnt;
void print_ans(int cur){
if(cur != m){
print_ans(pre[cur]);
printf(" %d", cur);
}
}
void dfs(int now, int step){
if(step < 20 && vis[m]) return ;
if(now == m && step == 20){
printf("%d: %d", ++cnt, m);
print_ans(pre[m]);
printf(" %d\n", m);
return ;
}
for(int i=0; i<3; i++){
int tp = city[now][i];
if(!vis[tp]){
vis[tp] = true;
pre[tp] = now;
dfs(tp, step+1);
vis[tp] = false; //搜完要恢复标记。。。
}
}
}
int main(){
#ifdef sxk
freopen("in.txt", "r", stdin);
#endif //sxk
int a, b, c;
for(int i=1; i<=20; i++){
scanf("%d%d%d", &a, &b, &c);
if(b > c) swap(b, c); //手动排序
if(a > b) swap(a, b);
if(b > c) swap(b, c);
city[i][0] = a, city[i][1] = b, city[i][2] = c;
}
while(scanf("%d", &m) == 1 && m){
memset(vis, false, sizeof(vis));
memset(pre, 0, sizeof(pre));
cnt = 0;
dfs(m, 0);
}
return 0;
}