Advertisement
Guest User

Untitled

a guest
Jan 28th, 2020
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int p[200005];
  6. set<int> el1[200005];
  7. set<int> el2[200005];
  8. pair<set<int>, set<int>> a[200005];
  9.  
  10. int GetSet(int v) {
  11. if (p[v] == v) {
  12. return v;
  13. }
  14. return p[v] = GetSet(p[v]);
  15. }
  16.  
  17. int GetAnswer(int v) {
  18. v = GetSet(v);
  19. return *(--a[v].first.end());
  20. }
  21.  
  22.  
  23. void UnionSet(int u, int v) {
  24. u = GetSet(u);
  25. v = GetSet(v);
  26. if (u == v) {
  27. return;
  28. }
  29. if (a[u].first.size() + a[u].second.size() < a[v].first.size() + a[v].second.size()) {
  30. swap(u, v);
  31. }
  32. p[v] = u;
  33. for (const auto& i : a[v].first) {
  34. if (i <= *(--a[u].first.end())) {
  35. a[u].first.insert(i);
  36. } else {
  37. a[u].second.insert(i);
  38. }
  39. if (a[u].first.size() < a[u].second.size()) {
  40. auto el = a[u].second.begin();
  41. a[u].second.erase(el);
  42. a[u].first.insert(*el);
  43. continue;
  44. }
  45. if (a[u].first.size() - a[u].second.size() > 1) {
  46. auto el = a[u].first.end();
  47. a[u].first.erase(a[u].first.end());
  48. a[u].second.insert(*(--el));
  49. }
  50. }
  51. for (const auto& i : a[v].second) {
  52. if (i <= *(--a[u].first.end())) {
  53. a[u].first.insert(i);
  54. } else {
  55. a[u].second.insert(i);
  56. }
  57. if (a[u].first.size() < a[u].second.size()) {
  58. auto el = a[u].second.begin();
  59. a[u].second.erase(el);
  60. a[u].first.insert(*el);
  61. continue;
  62. }
  63. if (a[u].first.size() - a[u].second.size() > 1) {
  64. auto el = a[u].first.end();
  65. a[u].first.erase(el);
  66. a[u].second.insert(*(--el));
  67. }
  68. }
  69.  
  70. }
  71.  
  72. int main()
  73. {
  74. ios_base::sync_with_stdio(0);
  75. freopen("input.txt", "r", stdin);
  76. freopen("output.txt", "w", stdout);
  77. int n, q;
  78. cin >> n >> q;
  79. for (int i = 1; i <= n; i++) {
  80. p[i] = i;
  81. a[i].first.insert(i);
  82. }
  83. for (int i = 0; i < q; i++) {
  84. int t, x, y;
  85. cin >> t;
  86. if (t == 1) {
  87. cin >> x >> y;
  88. UnionSet(x, y);
  89. }
  90. else {
  91. cin >> x;
  92. cout << GetAnswer(x) << "\n";
  93. }
  94. }
  95. return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement