2 条题解

  • 0
    @ 2023-4-15 16:48:35

    普通并查集,但是由于为字符串,所以用map存储关系

    注意merge时并非将 本人的祖先与祖先合并!

    #include <bits/stdc++.h>
    #define int long long int
    
    using namespace std;
    
    const int N = 1e5 + 7;
    map<string,string> bond;
    string s1,s; 
    
    string get(string x){
        if(bond[x] == x)return x;
        return bond[x] = get(bond[x]);
    }
    
    void merge(string x,string y){
        y = get(y);
        bond[x] = y;
    }
    
    signed main(){
        char ch = getchar();
        while(ch != '$'){
        if(ch == '#'){
            cin >> s;
            if(bond[s] == "")bond[s] = s;
        }
        if(ch == '+'){
            cin >> s1;
            merge(s1,s); 
        }
        if(ch == '?'){
            cin >> s;
            get(s);//更新祖先确保最早
            cout << s << " " << bond[s] << endl;
        }
            ch = getchar();
        }
        return 0;
    }
    

    信息

    ID
    398
    时间
    2000ms
    内存
    128MiB
    难度
    10
    标签
    递交数
    8
    已通过
    5
    上传者