Iamtui1010

hamilton.cpp

Jan 19th, 2022
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<vector>
  4. #include<climits>
  5.  
  6. #define long long long
  7. #define nln '\n'
  8.  
  9. const long I = LLONG_MAX;
  10.  
  11. using namespace std;
  12.  
  13. vector<vector<bool>> mtx;
  14. long n;
  15. vector<bool> pic;
  16. vector<long> pat, res;
  17. bool ok = 0;
  18.  
  19. void dfs(long i, long cnt)
  20. {
  21.     if (ok)
  22.         return;
  23.     if (cnt == n){
  24.         if (!mtx[i][1])
  25.             return;
  26.         res = pat;
  27.         ok = 1;
  28.         return;
  29.     }
  30.     for (long j = 1; j <= n; ++j)
  31.         if (mtx[i][j] && !pic[j]){
  32.             pic[j] = 1;
  33.             pat.push_back(j);
  34.             dfs(j, cnt+1);
  35.             pat.pop_back();
  36.             pic[j] = 0;
  37.         }
  38. }
  39.  
  40. int main()
  41. {
  42.     cin.tie(0)->sync_with_stdio(0);
  43.     cout.tie(0)->sync_with_stdio(0);
  44.     //freopen("hamilton.inp", "r", stdin);
  45.     long m;
  46.     cin >> n >> m;
  47.     mtx.resize(n+1);
  48.     for (long i = 0; i <= n; ++i)
  49.         mtx[i].resize(n+1, 0);
  50.     while (m--){
  51.         long x, y;
  52.         cin >> x >> y;
  53.         mtx[x][y] = 1;
  54.         mtx[y][x] = 1;
  55.     }
  56.  
  57.     pic.resize(n+1, 0);
  58.     pic[1] = 1;
  59.     dfs(1, 1);
  60.     cout << 1 << ' ';
  61.     for (const auto &i : res)
  62.         cout << i << ' ';
  63.     cout << 1 << nln;
  64.     cout << nln;
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment