Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // #### Zeinab
- #include<bits/stdc++.h>
- using namespace std;
- #define nl "\n"
- #define fi first
- #define se second
- #define pb push_back
- #define ll long long
- #define RV return void
- #define sz(x) int(x.size())
- #define all(v) v.begin(), v.end()
- #define rall(v) v.rbegin(), v.rend()
- #define cin(v) for(auto&x:v) cin >> x;
- #define cout(v) for(auto&x:v) cout << x << " ";
- int n , m , type , p , q;
- struct DSU{
- vector < int > Leader , Size , Sum ;
- DSU(int mxSize){
- Leader.assign(mxSize+5 , 0);
- Size.assign(mxSize+5 , 1);
- Sum.assign(mxSize+5 , 0);
- for(int i=0 ; i<=mxSize ; i++)
- Leader[i]=i , Sum[i]=i;
- }
- int FindLeader(int node){
- if(Leader[node]==node)
- return node;
- return Leader[node]=FindLeader(Leader[node]);
- }
- bool SameGroup(int u , int v ){
- return FindLeader(u)==FindLeader(v);
- }
- void MergeGroups(int u , int v ){
- int LeaderU = FindLeader(u);
- int LeaderV = FindLeader(v);
- if(LeaderU==LeaderV) return;
- if(Size[LeaderV] > Size[LeaderU])
- swap(LeaderU , LeaderV) , swap(u,v);
- Leader[v]=LeaderU;
- Size[LeaderU] +=Size[LeaderV];
- Sum[LeaderU] += Sum[LeaderV];
- Size[LeaderV]=0;
- Sum[LeaderV]=0;
- }
- void Move(int u , int v){
- // move u to v
- int LeaderU = FindLeader(u);
- int LeaderV = FindLeader(v);
- if(LeaderU==LeaderV) return;
- Leader[u]=LeaderV;
- Size[LeaderV] ++;
- Sum[LeaderV] += u;
- Sum[LeaderU] -=u;
- Size[LeaderU] --;
- }
- };
- void solve(){
- // union , move , return;
- while(cin >> n >> m){
- DSU d(n);
- while(m--){
- cin >> type;
- if(type==1){
- cin >> p >> q;
- // marge
- d.MergeGroups(p,q);
- }else if(type==2){
- cin >> p >> q;
- // move
- d.Move(p,q);
- }else{
- cin >> p;
- int leader = d.FindLeader(p);
- cout << d.Size[leader] << " "<< d.Sum[leader] << nl;
- }
- // for(int i =1 ; i <= 5; i++){
- // cout << i << " " << d.FindLeader(i) << " "<<d.Sum[ d.FindLeader(i)] << " " << d.Size[ d.FindLeader(i)] << nl;
- // }
- // cout << nl << nl;
- }
- }
- }
- int main(){
- ios_base::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);
- int t=1;
- // cin >> t ;
- for(int i=1 ; i <= t ; i++){
- // cout << "Case "<< i <<": " ;
- solve();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement