为何这个程序运行后Find函数输出只有空字符串
  • 板块P2814 家谱
  • 楼主10chen01
  • 当前回复1
  • 已保存回复1
  • 发布时间2024/4/2 20:59
  • 上次更新2024/4/3 07:25:32
查看原帖
为何这个程序运行后Find函数输出只有空字符串
753280
10chen01楼主2024/4/2 20:59

程序如下:

#include <cstdio>
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <map>

using namespace std;

//父节点或祖先节点
map<string, string> fa;

//并查集
string Find(string x){
    if(fa[x]==x) return x;
    else return fa[x]=Find(fa[x]); //路径压缩
}

//合并
void Union(string child, string father){
    fa[child] = father;
}

int main(){
    string cfa;
    while(true){
        char ch = getchar();
        if(ch == '#'){ //父节点
            string tmp;
            cin>>tmp;
            cfa = tmp;
        }else if(ch == '+'){ //子节点
            string tmp;
            cin>>tmp;
            Union(tmp,cfa);
        }else if(ch == '?'){ //查询是否在同一的集合中
            string tmp;
            cin>>tmp;
            cout<<tmp<<" "<<Find(tmp)<<endl;
        }else if(ch == '$') break;
    }
    return 0;
}

样例运行如下:

#George
+Rodney
#Arthur
+Gareth
+Walter
#Gareth
+Edward
?Edward
Edward <-这是输出
?Walter
Walter <-这是输出
?Rodney
Rodney <-这是输出
?Arthur
Arthur <-这是输出
$
2024/4/2 20:59
加载中...