nq1s788

проверка на двудольность

Jul 25th, 2025
856
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <set>
  3. #include <vector>
  4. #include <deque>
  5. #include <map>
  6. #include <cmath>
  7.  
  8. #define se second
  9. #define fi first
  10. #define mp make_pair
  11. #define pb push_back
  12.  
  13. typedef long long ll;
  14. typedef long double ld;
  15.  
  16. using namespace std;
  17.  
  18. vector<vector<int>> g;
  19. vector<bool> used;
  20. vector<int> col;
  21. vector<int> answ;
  22.  
  23. bool dfs(int h, int next_col) {
  24.     used[h] = true;
  25.     col[h] = next_col;
  26.     if (next_col == 0) answ.push_back(h + 1);
  27.     for (auto e : g[h]) {
  28.         if (col[e] == next_col) return false;
  29.         if (!used[e]) dfs(e, next_col ^ 1);
  30.     }
  31. }
  32.  
  33. int main() {
  34.     int n, m;
  35.     cin >> n >> m;
  36.     //vector<vector<int>> g(n, vector<int>(n, 0)); если бы объявляли локально
  37.     g.assign(n, vector<int>(n, 0));
  38.     used.assign(n, false);
  39.     while (m--) {
  40.         int a, b;
  41.         cin >> a >> b;
  42.         a--, b--;
  43.         g[a].push_back(b);
  44.         g[b].push_back(a);
  45.     }
  46.     col.assign(n, -1);
  47.     dfs(0, 0);
  48.     cout << (int)answ.size() << '\n';
  49.     for (auto e : answ) cout << e << ' ';
  50.     return 0;
  51. }
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment