Advertisement
tepyotin2

Cover It

Jul 7th, 2025
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int t;
  6.  
  7. int main(){
  8.     // freopen("coverit.in", "r", stdin);
  9.  
  10.     cin >> t;
  11.     while(t--){
  12.         int n, m;
  13.         cin >> n >> m;
  14.         vector<vector<int>> adj(n+1);
  15.         for(int i=0; i<m; i++){
  16.             int a, b;
  17.             cin >> a >> b;
  18.             adj[a].push_back(b);
  19.             adj[b].push_back(a);
  20.         }
  21.         /*
  22.         breadth first search to label the color where all of the values
  23.         are connected originally but we need to link the values and label
  24.         the color of 0 or 1 which the value we are currently on is opposite
  25.         of the value we are going to link it to so 0 would be 1 and 1 would
  26.         be 0
  27.         */
  28.         queue<int> q;
  29.         q.push(1);
  30.         vector<int> color(n+1, -1);
  31.         color[1] = 0;
  32.         while(!q.empty()){
  33.             int x = q.front();
  34.             q.pop();
  35.             for(int y: adj[x]){
  36.                 if(color[y] == -1){
  37.                     color[y] = color[x]^1;
  38.                     q.push(y);
  39.                 }
  40.             }
  41.         }
  42.         /*
  43.         after bfs we need to find which color has a smaller value because we know
  44.         we can use the values from that color to link it to every other value and
  45.         we need to chose the color which has a smaller amount and then we just
  46.         print the amount and print the indexes with the color we are using
  47.         */
  48.         int c0 = count(color.begin(), color.end(), 0);
  49.         int c1 = n-c0;
  50.         if(c0<=c1){
  51.             cout << c0 << '\n';
  52.             string s = "";
  53.             for(int i=1; i<=n; i++){
  54.                 if(color[i] == 0){
  55.                     cout << s << i;
  56.                     s = " ";
  57.                 }
  58.             }
  59.             cout << '\n';
  60.         }else{
  61.             cout << c1 << '\n';
  62.             string s = "";
  63.             for(int i=1; i<=n; i++){
  64.                 if(color[i] == 1){
  65.                     cout << s << i;
  66.                     s = " ";
  67.                 }
  68.             }
  69.             cout << '\n';
  70.         }
  71.     }
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement