-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathD_Replace_the_Numbers.cpp
More file actions
111 lines (91 loc) · 1.88 KB
/
D_Replace_the_Numbers.cpp
File metadata and controls
111 lines (91 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <limits>
#include <numeric>
#include <climits>
#define int long long
using namespace std;
const int MAX = 5e5 + 10;
class DSU2{
public:
vector<int> parent;
vector<int> size;
DSU2(int n){
parent.resize(n);
size.resize(n, 1);
for(int i = 0; i < n; i++){
parent[i] = i;
}
}
void unite(int a, int b){
a = findRoot(a);
b = findRoot(b);
if(a == b) return;
if(size[a] < size[b]){
parent[a] = b;
size[b] += size[a];
} else {
parent[b] = a;
size[a] += size[b];
}
}
int findRoot(int a){
if(a == parent[a]) return a;
return parent[a] = findRoot(parent[a]); // Path compression
}
};
void solve() {
int q;
cin >> q;
DSU2 dsu(MAX);
vector<int> result;
for(int i = 0; i < q; i++){
int type;
cin >> type;
if(type == 1){
int x;
cin >> x;
result.push_back(x);
}
else if(type == 2){
int x, y;
cin >> x >> y;
int root_x = dsu.findRoot(x);
int root_y = dsu.findRoot(y);
if(root_x != root_y){
dsu.unite(x, y);
}
}
}
for(int &val : result){
val = dsu.findRoot(val);
}
for(int x : result){
cout << x << " ";
}
cout << '\n';
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int _t = 1;
// cin >> _t;
while(_t--){
solve();
}
return 0;
}