Advertisement
coderchesser

bipartite

Oct 12th, 2024
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | Source Code | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int n;
  5. vector<bool> visited;
  6. vector<int> red; // even
  7. vector<int> blue; // odd
  8. vector<vector<int>> graph;
  9.  
  10. void dfs(int source, int counter){
  11.     if (visited[source]){
  12.         return;
  13.     }
  14.     else{
  15.         visited[source] = true;
  16.         if (counter % 2 == 0){
  17.             red.push_back(source);
  18.         }
  19.         else{
  20.             blue.push_back(source);
  21.         }
  22.         for (int child : graph[source]){
  23.             if (!visited[child]){
  24.                 dfs(child, (counter + 1)%2);
  25.             }
  26.         }
  27.     }
  28. }
  29.  
  30. int main(){
  31.     int t;
  32.     cin >> t;
  33.     while(t--){
  34.         int n, m;
  35.         cin >> n >> m;
  36.         for (int i = 0; i < m; i++){
  37.             int u, v;
  38.             cin >> u >> v;
  39.         }
  40.         dfs(0, 0);
  41.         int red_nodes = red.size();
  42.         int blue_nodes = blue.size();
  43.         cout << min(red_nodes, blue_nodes) << endl;
  44.         if (blue_nodes <= red_nodes){
  45.             for (auto i : blue){
  46.                 cout << i << " ";
  47.             }
  48.         }
  49.         else{
  50.             for (auto i : red){
  51.                 cout << i << " ";
  52.             }
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement