有偿调代码
查看原帖
有偿调代码
757597
HopesandDreams楼主2022/11/25 11:34

RT,代码有注释。

#include<iostream>
#include<map>
using namespace std;

const int MAXN = 1e4 * 5 + 5;
struct node{ //存储每个人的名字和号码
    int fa,id;
    string name;
} a[MAXN];
int Q[MAXN]; //存储查询的号码
map<string,int> MP; //对应名字和号码
int cnt = 0,temp,k = 0;
char c;
string s;

string FIND(int d){ //并查集标准路径压缩
    if (a[d].fa == a[d].id) return a[d].name;
    return FIND(a[a[d].fa].id);
}
int main(){
    while(true){
        cin>>c;
        if (c == '$') break;
        if (c == '#'){
            cin>>s; 
            if (MP[s] == 0){ //添加一个人 
                MP[s] = ++cnt;
                a[cnt].fa = cnt;
                a[cnt].id = cnt;
                a[cnt].name = s;
            }
            temp = MP[s]; //存父亲的名字
        }
        if (c == '+'){
            cin>>s;
            if (MP[s] == 0) { //添加儿子
                MP[s] = ++cnt;
                a[cnt].id = cnt;
                a[cnt].name = s;
            }
            a[cnt].fa = temp; //设父亲
        }
        if (c == '?'){
            cin>>s;
            if (MP[s] == 0) { //如果询问的人没有出现过
                MP[s] = ++cnt;
                Q[++k] = a[cnt].fa = cnt = a[cnt].id = cnt; //存储询问号码及信息
                a[cnt].name = s;
            }
            else Q[++k] = MP[s];
        }
    }
    //for (int i = 1;i <= cnt;i++) cout<<a[i].fa<<endl;
    for (int i = 1;i <= k;i++){
        cout<<a[Q[i]].name<<" "<<FIND(Q[i])<<endl; //处理询问
    }
}

帮忙调的人悬赏关注。

2022/11/25 11:34
加载中...