Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /***
- СНМ (Система непересекающихся множеств)
- ***/
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e6 + 5;
- int n, q;
- int p[N];
- int sz[N];
- int find_set(int a) {
- if (p[a] == a) return a;
- p[a] = find_set(p[a]);
- return p[a];
- }
- void union_set(int a, int b) {
- a = find_set(a);
- b = find_set(b);
- if (a == b) {
- return;
- }
- if (sz[a] < sz[b]) {
- p[b] = a;
- sz[b] = sz[b] + sz[a];
- } else {
- p[a] = b;
- sz[a] = sz[a] + sz[b];
- }
- }
- int main(){
- cin >> n >> q;
- for (int i = 1; i <= n; i++) {
- p[i] = i;
- sz[i] = 1;
- }
- for (int i = 1; i <= q; i++) {
- int type;
- cin >> type;
- if (type == 1) {
- int u, v;
- cin >> u >> v;
- union_set(u, v);
- }
- if (type == 2) {
- int a, b;
- cin >> a >> b;
- if (find_comp(a) == find_comp(b)) {
- cout << "YES\n";
- } else {
- cout << "NO\n";
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment