Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- using namespace std;
- const int maxn = 2e5 + 10;
- int idx[maxn], sz[maxn];
- void init() {
- for(int i = 0; i < maxn; i++) {
- idx[i] = i;
- sz[i] = 1;
- }
- }
- int find_root(int x) {
- while(x != idx[x]) {
- idx[x] = idx[idx[x]];
- x = idx[x];
- }
- return x;
- }
- bool check_elems(int A, int B) {
- int rootA = find_root(A);
- int rootB = find_root(B);
- return(rootA == rootB);
- }
- void union_elems(int A, int B) {
- int rootA = find_root(A);
- int rootB = find_root(B);
- if(rootA != rootB) {
- if(sz[rootA] < sz[rootB]) {
- sz[rootB] += sz[rootA];
- idx[rootA] = idx[rootB];
- }
- else {
- sz[rootA] += sz[rootB];
- idx[rootB] = idx[rootA];
- }
- }
- }
- int main() {
- init();
- while(true) {
- string s;
- cin >> s;
- int a, b;
- cin >> a >> b;
- if(s == "union") {
- union_elems(a, b);
- }
- else {
- cout << check_elems(a, b) << endl;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment