Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int p[200005];
- set<int> el1[200005];
- set<int> el2[200005];
- pair<set<int>, set<int>> a[200005];
- int GetSet(int v) {
- if (p[v] == v) {
- return v;
- }
- return p[v] = GetSet(p[v]);
- }
- int GetAnswer(int v) {
- v = GetSet(v);
- return *(--a[v].first.end());
- }
- void UnionSet(int u, int v) {
- u = GetSet(u);
- v = GetSet(v);
- if (u == v) {
- return;
- }
- if (a[u].first.size() + a[u].second.size() < a[v].first.size() + a[v].second.size()) {
- swap(u, v);
- }
- p[v] = u;
- for (const auto& i : a[v].first) {
- if (i <= *(--a[u].first.end())) {
- a[u].first.insert(i);
- } else {
- a[u].second.insert(i);
- }
- if (a[u].first.size() < a[u].second.size()) {
- auto el = a[u].second.begin();
- a[u].second.erase(el);
- a[u].first.insert(*el);
- continue;
- }
- if (a[u].first.size() - a[u].second.size() > 1) {
- auto el = a[u].first.end();
- a[u].first.erase(a[u].first.end());
- a[u].second.insert(*(--el));
- }
- }
- for (const auto& i : a[v].second) {
- if (i <= *(--a[u].first.end())) {
- a[u].first.insert(i);
- } else {
- a[u].second.insert(i);
- }
- if (a[u].first.size() < a[u].second.size()) {
- auto el = a[u].second.begin();
- a[u].second.erase(el);
- a[u].first.insert(*el);
- continue;
- }
- if (a[u].first.size() - a[u].second.size() > 1) {
- auto el = a[u].first.end();
- a[u].first.erase(el);
- a[u].second.insert(*(--el));
- }
- }
- }
- int main()
- {
- ios_base::sync_with_stdio(0);
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- int n, q;
- cin >> n >> q;
- for (int i = 1; i <= n; i++) {
- p[i] = i;
- a[i].first.insert(i);
- }
- for (int i = 0; i < q; i++) {
- int t, x, y;
- cin >> t;
- if (t == 1) {
- cin >> x >> y;
- UnionSet(x, y);
- }
- else {
- cin >> x;
- cout << GetAnswer(x) << "\n";
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement