Advertisement
Five_NT

Tema 6 | Cicruit Hamiltonian

May 27th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. //
  2. #include<fstream>
  3. #include<iostream>
  4.  
  5. using namespace std;
  6.  
  7. #define MAX_SIZE 50
  8.  
  9. int m[MAX_SIZE][MAX_SIZE], k, v_sol[MAX_SIZE], n;
  10.  
  11.  
  12. bool solutie = false;
  13.  
  14. void citire()
  15. {
  16.     ifstream f("date.in");
  17.     f >> n;
  18.     for(int i=1; i<=n; i++)
  19.         for(int j=1; j<=n; j++)
  20.             f >> m[i][j];
  21.     f.close();
  22. }
  23.  
  24. int cont(int k)
  25. {
  26.     int i;
  27.     for(int i=1; i<k; i++)
  28.         if(v_sol[i] == v_sol[k])
  29.             return 0;
  30.     if(k > 1)
  31.         if(m[ v_sol[k] ][ v_sol[k-1] ] == 0)
  32.             return 0;
  33.     if(k == n)
  34.         if(m[ v_sol[n] ][ v_sol[1] ] == 3)
  35.             return 0;
  36.     return 1;
  37. }
  38.  
  39. void afis()
  40. {
  41.     for(int i = 1; i <= n; i++)
  42.         cout << v_sol[i] << " ";
  43.     cout << v_sol[1] << '\n';
  44. }
  45.  
  46. void back()
  47. {
  48.     int k = 1;
  49.     v_sol[k] = 0;
  50.     do
  51.     {
  52.         while(v_sol[k] < n)
  53.         {
  54.             v_sol[k]++;
  55.             if(cont(k))
  56.                 if(k == n)
  57.                 {
  58.                     solutie = true;
  59.                     afis();
  60.                     break;
  61.                 }
  62.                 else
  63.                 {
  64.                     k++;
  65.                     v_sol[k] = 0;
  66.                 }
  67.             if(solutie)
  68.                 break;
  69.         }
  70.         k--;
  71.     }
  72.     while(k);
  73. }
  74. int main()
  75. {
  76.     citire();
  77.     back();
  78.     if(solutie == false)
  79.         cout << "Nu avem niciun circuit hamiltonian.";
  80.  
  81.     return 0;
  82. }
  83. // Exemplu:
  84. /*
  85. 6
  86. 0 1 0 1 0 1
  87. 1 0 1 1 1 0
  88. 0 1 0 1 0 1
  89. 1 1 1 0 1 0
  90. 0 1 0 1 0 1
  91. 1 0 1 0 0 1
  92. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement