并查集,11分,可能控制深度出错
查看原帖
并查集,11分,可能控制深度出错
727556
wangziwenhk楼主2023/11/5 14:18
#include <bits/stdc++.h>

using namespace std;
int father[30010];
int dep[30010];
int find(int x) {
    if (father[x] == x)return x;
    else{
        int temp = father[x];
        father[x]=find(father[x]);
        dep[x] += dep[temp];
        return father[x];
    }
}

void add(int x, int y) {
    int tx = find(x);
    int ty = find(y);
    if (tx == ty)return;
    father[tx] = ty;
    dep[x] = dep[y];
}

void init(int n) {
    for (int i = 1; i <= n; i++) {
        father[i] = i;
        dep[i]=1;
    }
}

int main() {
    cin.tie();
    cout.tie();
    ios::sync_with_stdio(0);
    int T;
    cin>>T;
    init(30005);
    while (T--) {
        char ch;
        int x, y;
        cin >> ch >> x >> y;
        if (ch == 'M') {
            add(x, y);
        }
        if (ch == 'C') {
            if (find(x) == find(y)){
                if(x==y)cout<<0<<endl;
                else cout << abs(dep[x]-dep[y])-1 << endl;
            }
            else cout << -1<< endl;
        }
    }
    return 0;
}



2023/11/5 14:18
加载中...