Advertisement
coloriot

HA_30_NoCheating(2)

Nov 8th, 2024
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. class Graph {
  8. private:
  9.     vector<vector<int> > adj;
  10.     vector<int> color;
  11.  
  12. public:
  13.     Graph(int n) {
  14.         adj.resize(n);
  15.         color.resize(n, -1);
  16.     }
  17.  
  18.     void add_edge(int u, int v) {
  19.         adj[u].push_back(v);
  20.         adj[v].push_back(u);
  21.     }
  22.  
  23.     bool is_bipartite() {
  24.         int n = adj.size();
  25.         for (int i = 0; i < n; ++i) {
  26.             if (color[i] == -1) {
  27.                 if (!bfs_check(i)) {
  28.                     return false;
  29.                 }
  30.             }
  31.         }
  32.         return true;
  33.     }
  34.  
  35.     bool bfs_check(int start) {
  36.         queue<int> q;
  37.         q.push(start);
  38.         color[start] = 0;
  39.  
  40.         while (!q.empty()) {
  41.             int u = q.front();
  42.             q.pop();
  43.  
  44.             for (size_t i = 0; i < adj[u].size(); ++i) {
  45.                 int v = adj[u][i];
  46.                 if (color[v] == -1) {
  47.                     color[v] = 1 - color[u];
  48.                     q.push(v);
  49.                 } else if (color[v] == color[u]) {
  50.                     // Если соседняя вершина имеет тот же цвет, граф не двудольный
  51.                     return false;
  52.                 }
  53.             }
  54.         }
  55.         return true;
  56.     }
  57. };
  58.  
  59. int main() {
  60.     int N, M;
  61.     cin >> N >> M;
  62.  
  63.     Graph graph(N);
  64.  
  65.     for (int i = 0; i < M; ++i) {
  66.         int u, v;
  67.         cin >> u >> v;
  68.         u--;
  69.         v--;
  70.         graph.add_edge(u, v);
  71.     }
  72.  
  73.     if (graph.is_bipartite()) {
  74.         cout << "YES" << endl;
  75.     } else {
  76.         cout << "NO" << endl;
  77.     }
  78.  
  79.     return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement