Advertisement
_no0B

Untitled

Dec 24th, 2021
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define LL long long
  3. #define N ((int)1e5 + 8)
  4. #define MAX ((int)1e9 + 8)
  5. #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL)
  6.  
  7. using namespace std;
  8.  
  9. vector < pair < int , int > > edge[N]; /// edge[i] = list of adjacent nodes of node 'i'
  10.  
  11. int col[N];
  12.  
  13. vector < int > com[2];
  14.  
  15. bool dfs(int n , int c)
  16. {
  17.     if(vis[n] == 1){
  18.         if(c == col[n]) return 1;
  19.         return 0;
  20.     }
  21.  
  22.     com[c].push_back(n);
  23.     vis[n] = 1;
  24.     col[n] = c;
  25.     bool res = 1;
  26.     for(auto p:edge[n]){
  27.         int a = p.first , w = p.second;
  28.         res &= dfs(a , c^w);
  29.     }
  30.     return res;
  31. }
  32.  
  33. void Insert(vector < int >& vecA , vector < int >& vecB)
  34. {
  35.     for(int a:vecA) vecB.push_back(a);
  36. }
  37.  
  38. pair < int , vector < int > > Solve(char finalCol , vector < pair < pair < int , int > , char > >& edges)
  39. {
  40.     Init(n);
  41.     for(auto p:edges){
  42.         int a = p.first.first , b = p.first.second;
  43.         int w = (p.second != finalCol);
  44.         AddEdge(a , b , w);
  45.         AddEdge(b , a , w);
  46.     }
  47.  
  48.     vector < int > ans;
  49.  
  50.     for(int i = 1 ; i <= n ; i++){
  51.         if(vis[i]  == 0){
  52.             com[0].clear();
  53.             com[1].clear();
  54.             if(dfs(i , 0) == 0) return {-1,ans};
  55.             if(com[0].size() < com[1].size()) Insert(com[0] , ans);
  56.             else Insert(com[1], ans);
  57.         }
  58.     }
  59.     return {ans.size() , ans};
  60. }
  61.  
  62.  
  63. int main()
  64. {
  65.     /// problem link: https://codeforces.com/contest/664/problem/D
  66.     int n , m ;
  67.     cin>>n>>m;
  68.     vector < pair < pair < int , int > , char > > edges;
  69.     while(m--){
  70.         int a , b , w;
  71.         char c;
  72.         cin>>a>>b>>c;
  73.         edges.push_back({{a,b} , c});
  74.  
  75.     }
  76.  
  77.     pair < int , vector < int > > ans1 , ans2;
  78.     ans1 = Solve('R' , edges);
  79.     ans2 = Solve('B' , edges);
  80.  
  81.     if(ans1.first != -1 && ans2.first != -1){
  82.         if(ans1.second.size() < ans2.second.size()) Print(ans1.second);
  83.         else Print(ans2.second);
  84.     }
  85.     else if(ans1.first != -1) Print(ans1.second);
  86.     else if(ans2.first != -1) Print(ans2.second);
  87.     else cout<<"-1\n";
  88. }
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement