【題解】Codeforces EDU Course-2 Lesson-7-1 A. Disjoint Sets Union

【題目敘述】http://codeforces.com/edu/course/2/lesson/7/1/practice/contest/289390/problem/A

#include <iostream>
using namespace std;
 
int n, m, p[100005];
 
int pa(int x){
    if (x == p[x]) return x;
    return p[x] = pa(p[x]);
}
 
int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++){
        p[i] = i;
    }
    string s;
    for (int i = 0, u, v; i < m; i++){
        cin >> s >> u >> v;
        if (s == "union"){
            u = pa(u);
            v = pa(v);
            p[v] = u;
        }
        else{
            if (pa(u) == pa(v)) cout << "YES\n";
            else cout << "NO\n";
        }
    }
}
分享本文 Share with friends