Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <set>
  4. using namespace std;
  5.  
  6. class Modunionfind{
  7.     int n;
  8.     vector<int> roots;
  9.     vector<int> sums;
  10.     vector<set<int>> elements;
  11.     public:
  12.     Modunionfind(int N):n(N){
  13.         roots.resize(n);
  14.         sums.resize(n);
  15.         elements.resize(n);
  16.         for (int i=0;i!=n;++i ){roots[i]=i;elements[i].insert(i);sums[i]=i+1;}
  17.     };
  18.     int get_size(int x){return elements[roots[x]].size();}
  19.     int get_sum(int x){return sums[roots[x]];}
  20.     void unite(int from, int to){
  21.         if (roots[from]==roots[to]) return;
  22.         if (get_size(from)>get_size(to)) swap(from,to);
  23.         sums[roots[to]]+=sums[roots[from]];
  24.         int rf=roots[from];
  25.         for (int x:elements[rf]){
  26.             elements[roots[to]].insert(x);
  27.             roots[x]=roots[to];
  28.         }
  29.         //elements[rf].clear();
  30.     }
  31.     void move(int from, int to){
  32.         if (roots[from]==roots[to]) return;
  33.         elements[roots[from]].erase(from);
  34.         sums[roots[from]]-=from+1;
  35.         roots[from]=roots[to];
  36.         sums[roots[to]]+=from+1;
  37.         elements[roots[to]].insert(from);
  38.     }
  39. };
  40.  
  41. void solve(int n,int m){
  42.     Modunionfind mf(n);
  43.     for (int i=0; i!=m;++i){
  44.         int a;
  45.         cin>>a;
  46.         if (a==1){
  47.             int b,c;
  48.             cin>>b>>c;
  49.             --b;--c;
  50.             mf.unite(b,c);
  51.         }
  52.         else if (a==2){
  53.             int b,c;
  54.             cin>>b>>c;
  55.             --b;--c;
  56.             mf.move(b,c);
  57.         }else{
  58.             int b;
  59.             cin>>b;
  60.             --b;
  61.             cout<<mf.get_size(b)<<" "<<mf.get_sum(b)<<"\n";
  62.         }
  63.     }
  64. }
  65. int main(){
  66.     ios::sync_with_stdio(0);
  67.     int n,m;
  68.     while (cin>>n>>m)solve(n,m);
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement