Advertisement
monyca98

verificare de graf hamiltonian

May 24th, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include<iostream>
  2. #include<fstream>
  3. #include<vector>
  4. typedef std::vector<std::vector<int>> matrix;
  5. matrix g;
  6. int n, m;  //no of vertices and edges
  7.  
  8. void read()
  9. {
  10.     std::ifstream in("file.txt");
  11.     if (in.is_open())
  12.     {
  13.         in >> n >> m;
  14.         //init a nxn matrix with 0
  15.         g.resize(n);
  16.         for (int i = 0; i < n; i++)
  17.             g[i].assign(n, 0);
  18.         int x, y;
  19.         for (int i = 0; i < m; i++)
  20.         {
  21.             in>> x >> y;
  22.             g[x][y] = 1;
  23.             g[y][x] = 1;
  24.         }
  25.     }
  26.     else
  27.         std::cout << "Unable to open the file!\n";
  28. }
  29.  
  30. int is_hamiltonian()
  31. {
  32.     if (n < 3)
  33.         return 0;
  34.     int grade = 0;
  35.     for (int i = 0; i < n; i++)
  36.     {
  37.         grade = 0;
  38.         for (int j = 0; j < n; j++)
  39.             if (g[i][j] == 1)
  40.                 grade++;
  41.         if (grade < n / 2)
  42.             return 0;
  43.     }
  44.     return 1;
  45. }
  46. int main()
  47. {
  48.     read();
  49.     if (is_hamiltonian())
  50.         std::cout << "Is hamiltonian\n";
  51.     else
  52.         std::cout << "Isn't hamiltonian\n";
  53.     return 0;
  54. }
  55.  
  56. /*
  57. 6
  58. 11
  59. 0 1
  60. 0 4
  61. 0 5
  62. 1 2
  63. 1 4
  64. 2 3
  65. 2 4
  66. 3 4
  67. 4 5
  68. 1 5
  69. 1 3
  70.  
  71. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement