哈密顿绕行世界问题 HDU - 2181

原题链接

考察:搜索

思路:

       bfs或dfs.dfs代码短一点.bfs可以用二进制标记去过的城市.不必用数组,同理dfs.听说本题数据水,可能本蒟蒻的代码有点问题.

 1 #include <iostream> 
 2 #include <cstring>
 3 #include <vector>
 4 using namespace std;
 5 const int N = 25;
 6 int n = 20,sz,sta,path[N];
 7 bool g[N][N];
 8 vector<int> v[1<<N-5];
 9 void dfs(int u,int now,int cnt)
10 {
11     if(now==(1<<20)-1)
12     {
13         if(g[u][sta-1])
14         {
15             sz++;
16             v[sz].push_back(sta);
17             for(int i=1;i<=cnt;i++) v[sz].push_back(path[i]+1);
18             v[sz].push_back(sta);
19         }
20         return;
21     }
22     for(int i=0;i<20;i++)
23       if(!(now>>i&1)&&g[i][u])
24       {
25           path[cnt+1] = i;
26           dfs(i,now|(1<<i),cnt+1);
27       }
28 }
29 int main()
30 {
31     for(int i=1;i<=n;i++) 
32     {
33         int a,b,c; scanf("%d%d%d",&a,&b,&c);
34         a--,b--,c--;
35         g[i-1][a] = g[i-1][b] = g[i-1][c] = 1;
36         g[a][i-1] = g[b][i-1] = g[c][i-1] = 1;
37     }
38     while(scanf("%d",&sta)&&sta)
39     {
40         dfs(sta-1,1<<sta-1,0);
41         for(int i=1;i<=sz;i++)
42         {
43             printf("%d:  ",i);
44             for(int j=0;j<v[i].size();j++)
45               printf("%d%c",v[i][j],j+1==v[i].size()?'\n':' ');
46         }
47     }
48     return 0;
49 }

 

posted @ 2021-04-21 23:27  acmloser  阅读(46)  评论(0编辑  收藏  举报