Advertisement
den4ik2003

Untitled

Apr 5th, 2022
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. enum class Colour { White, Grey, Black };
  2.  
  3. template <bool IsOriented>  // NOLINT
  4. class Graph {
  5.  private:
  6.   int number_of_vertex_ = 0;
  7.   vector<vector<int>> neighbours_;
  8.   vector<int> parent_;
  9.   vector<Colour> colour_;
  10.   vector<int> cycle_;
  11.   int flag_;
  12.  
  13.  public:
  14.   Graph(int num_of_vert)
  15.     : number_of_vertex_(num_of_vert),
  16.       neighbours_(vector<vector<int>>(num_of_vert)),
  17.       parent_(vector<int>(num_of_vert)),
  18.       colour_(vector<Colour>(num_of_vert, Colour::White)),
  19.       flag_(0) {}
  20.  
  21.   void AddEdge(int begin, int end) {
  22.     if constexpr (!IsOriented) {
  23.       neighbours_[begin - 1].push_back(end - 1);
  24.     }
  25.     neighbours_[end - 1].push_back(begin - 1);
  26.   }
  27.  
  28.   std::optional<vector<int>> TryFindCycleInComponent(int vertex, int parent) {
  29.     parent_[vertex] = parent;
  30.     colour_[vertex] = Colour::Grey;
  31.     for (int to : neighbours_[vertex]) {
  32.       if (flag_ == 1) {
  33.         break;
  34.       }
  35.       if (colour_[to] == Colour::Black) {
  36.         continue;
  37.       }
  38.       if (colour_[to] == Colour::Grey) {
  39.         std::cout << "YES\n";
  40.         flag_ = 1;
  41.         vector<int> cycle;
  42.         int start_cycle = vertex;
  43.         while (start_cycle != to) {
  44.           cycle.push_back(start_cycle + 1);
  45.           start_cycle = parent_[start_cycle];
  46.         }
  47.         cycle.push_back(to + 1);
  48.         for (int i = cycle.size() - 1; i >= 0; --i) {
  49.           std::cout << cycle[i] << " ";
  50.         }
  51.         colour_[vertex] = Colour::Black;
  52.         return {cycle};
  53.       }
  54.       TryFindCycleInComponent(to, vertex);
  55.     }
  56.     colour_[vertex] = Colour::Black;
  57.     return {};
  58.   }
  59.  
  60.   std::optional<vector<int>> TryFindCycleInGraph() {
  61.     for (int i = 0; i < number_of_vertex_; ++i) {
  62.       if (colour_[i] == Colour::White) {
  63.         TryFindCycleInComponent(i, -1);
  64.       }
  65.       if (flag_ == 1) {
  66.         return TryFindCycleInComponent(i, -1);
  67.       }
  68.     }
  69.     return {};
  70.   }
  71. };
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement