Maruf_Hasan

virtual frnd//disjoint set

Mar 26th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define M 1000000
  4. int arr[M];
  5. int si[M];
  6.  
  7. void initialize(int N)
  8. {
  9. for(int i=0;i<=N;i++)
  10. {
  11. arr[i]=i;//initialize kortesi
  12. si[i]=1;//size 1 kore nissi jehetu prothome node e ekta element thake
  13. }
  14. }
  15. int root(int i)
  16. {
  17. while(arr[i]!=i)
  18. {
  19. i=arr[i];//jotokkhn root paitesi na root ber kortesi
  20. }
  21. return i;//root return kortesi
  22. }
  23. int weighted_union(int A,int B)
  24. {
  25. if(A==B)
  26. return 1;//same hole return 1
  27. int root_A=root(A);//checking root
  28. int root_B=root(B);
  29. if(root_A==root_B)
  30. return si[root_A];//same root hole just size return kortesi
  31.  
  32. if(si[root_A]<si[root_B])//size check kortesi
  33. {//jetar size boro oita root ke choto tar root banassi
  34. arr[root_A]=arr[root_B];//aer root b ek banaitesi;
  35. // cout<<si[root_A]<<" "<<si[root_B]<<endl;
  36. si[root_B]+=si[root_A];
  37. //cout<<si[root_B]<<endl;
  38. return si[root_B];
  39. }
  40. else
  41. {
  42. arr[root_B]=arr[root_A];//b er root a ke banaitesi
  43. // cout<<si[root_A]<<" "<<si[root_B]<<endl;
  44. si[root_A]+=si[root_B];//as a root so a er root banai eitar total element bartese
  45. //cout<<si[root_A]<<endl;
  46. return si[root_A];
  47. }
  48. }
  49. int main()
  50. {
  51. int t;
  52. cin>>t;
  53. while(t--)
  54. {
  55. int j=1;
  56. string a,b;
  57. int n;
  58. cin>>n;
  59. initialize(2*n);
  60. map<string,int>mp;
  61. for(int i=0;i<n;i++)
  62. {
  63. cin>>a>>b;
  64. if(mp[a]==0)
  65. {
  66. mp[a]=j++;
  67. // cout<<a<<" "<<mp[a]<<endl;
  68. }
  69. if(mp[b]==0)
  70. {
  71. mp[b]=j++;
  72. // cout<<b<<" "<<mp[b]<<endl;
  73. }
  74. int ans=weighted_union(mp[a],mp[b]);
  75. cout<<ans<<endl;
  76. }
  77. memset(si,1,sizeof si);
  78. memset(arr,0,sizeof arr);
  79. mp.clear();
  80. }
  81. return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment