Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- #define M 1000000
- int arr[M];
- int si[M];
- void initialize(int N)
- {
- for(int i=0;i<=N;i++)
- {
- arr[i]=i;//initialize kortesi
- si[i]=1;//size 1 kore nissi jehetu prothome node e ekta element thake
- }
- }
- int root(int i)
- {
- while(arr[i]!=i)
- {
- i=arr[i];//jotokkhn root paitesi na root ber kortesi
- }
- return i;//root return kortesi
- }
- int weighted_union(int A,int B)
- {
- if(A==B)
- return 1;//same hole return 1
- int root_A=root(A);//checking root
- int root_B=root(B);
- if(root_A==root_B)
- return si[root_A];//same root hole just size return kortesi
- if(si[root_A]<si[root_B])//size check kortesi
- {//jetar size boro oita root ke choto tar root banassi
- arr[root_A]=arr[root_B];//aer root b ek banaitesi;
- // cout<<si[root_A]<<" "<<si[root_B]<<endl;
- si[root_B]+=si[root_A];
- //cout<<si[root_B]<<endl;
- return si[root_B];
- }
- else
- {
- arr[root_B]=arr[root_A];//b er root a ke banaitesi
- // cout<<si[root_A]<<" "<<si[root_B]<<endl;
- si[root_A]+=si[root_B];//as a root so a er root banai eitar total element bartese
- //cout<<si[root_A]<<endl;
- return si[root_A];
- }
- }
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int j=1;
- string a,b;
- int n;
- cin>>n;
- initialize(2*n);
- map<string,int>mp;
- for(int i=0;i<n;i++)
- {
- cin>>a>>b;
- if(mp[a]==0)
- {
- mp[a]=j++;
- // cout<<a<<" "<<mp[a]<<endl;
- }
- if(mp[b]==0)
- {
- mp[b]=j++;
- // cout<<b<<" "<<mp[b]<<endl;
- }
- int ans=weighted_union(mp[a],mp[b]);
- cout<<ans<<endl;
- }
- memset(si,1,sizeof si);
- memset(arr,0,sizeof arr);
- mp.clear();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment