bhupixb

Disjoint set union

Jun 23rd, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int N = 100 * 100 * 10 + 5;
  4. int parent[N], size1[N];
  5. vector< vector < int > > v(20);
  6.  
  7. void make_set(int n, int x = 1){
  8. if(x > n)return;
  9. parent[x] = x;
  10. make_set(n, x + 1);
  11. }
  12. // iterative find
  13. int find(int x){
  14. while(x != parent[x])x = parent[x];
  15. return x;
  16. }
  17. /* recursive find
  18. int find(int x){
  19.  
  20. if(x != parent[x])x = find(parent[x]);
  21. return parent[x];
  22.  
  23. }*/
  24. /*find by path compression
  25. int find(int x) {
  26. return x == Parent[x] ? x : Parent[x] = find(Parent[x]);
  27. }
  28. int find(int x){
  29. if( parent[x] != x ){
  30. parent[x] = find(parent[x]) ;
  31. }
  32. return parent[x];
  33. }*/
  34. void merge_set(int x, int y){
  35. int rep_x = find(x);
  36. int rep_y = find(y);
  37.  
  38. if(rep_y == rep_x)return;
  39.  
  40. if(size1[rep_x] > size1[rep_y]){
  41. parent[rep_y] = rep_x;
  42. size1[rep_x] += size1[rep_y];
  43. }
  44.  
  45. else {
  46. parent[rep_x] = rep_y;
  47. size1[rep_y] += size1[rep_x];
  48. }
  49. }
  50. int main()
  51. {
  52. char ch;int x, y, n, q, child;
  53.  
  54. scanf("%d %d", &n, &q);
  55. make_set(n);
  56. for(int i = 1; i <= n; i++)size1[i] = 1;
  57. //for(int i = 1; i < 4; i++)cout << size1[i] << ' ';
  58. //for(int i = 1; i < 4; i++)cout << parent[i] << ' ';
  59.  
  60. for(int i=0; i<q; i++) {
  61. cin >> ch;
  62. if(ch == 'Q'){
  63. cin >> child;
  64. cout << size1[find(child)] << '\n';
  65. }
  66. else{
  67. cin >> x >> y;
  68. merge_set(x, y);
  69. }
  70. }
  71. // for(int i=1; i<=n; i++) if(!seen[i]) dfs(i);
  72. return 0;
  73. }
Add Comment
Please, Sign In to add comment