原题链接:https://www.acwing.com/problem/content/description/4232/
思路很像全排列,运用压缩状态存储,注意细节
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=25;
bool st[N][N];
int path[N];
int n,cnt;
void dfs(int u,int state,int k)
{
if(k!=0&&k!=20&&u==n) return;
if(k==20){
if(u==n)
{
cout<<cnt++<<": ";
for(int i=0;i<=k;i++) cout<<path[i]<<' ';
cout<<endl;
}
return;
}
for(int i=0;i<20;i++)
{
if(!st[u][i+1]) continue;
if(state>>i&1) continue;
path[k+1]=i+1;
dfs(i+1,state+(1<<i),k+1);
}
}
int main()
{
for(int i=1;i<=20;i++)
{
int a,b,c;
cin>>a>>b>>c;
st[i][a]=st[a][i]=st[b][i]=st[i][b]=st[c][i]=st[i][c]=true;
}
while(cin>>n,n)
{
cnt=1;
path[0]=n;
dfs(n,0,0);
}
return 0;
}
标签:哈密顿,int,世界,dfs,st,绕行,state,path,include
From: https://www.cnblogs.com/linearlearn/p/17294485.html