题解 | #找出直系亲属#

找出直系亲属

https://www.nowcoder.com/practice/2c958d09d29f46798696f15ae7c9703b

用并查集,没有写union操作,测试也没问题。find改为查找特定的res,返回迭代次数iter。最后根据iter决定输出。

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int child[30];
int height[30];
void initial(){
    for(int i=0;i<100;i++){
        child[i]=i;
        height[i]=0;
    }
}
int find(int x,int des){
    int tmp=x,iter=0;
    while(child[tmp]!=tmp){
        if(tmp==des){
            return iter;
        }
        else{
            iter++;
            tmp=child[tmp];
        }
    }
    if(tmp==des)
        return iter;
    else return 0;
}
int main() {
    int a, b;
    while (cin >> a >> b) { // 注意 while 处理多个 case
        char x,y,z;
        initial();
        for(int i=0;i<a;i++){
            cin>>x>>y>>z;
            if(y!='-'){
                child[y-'A']=x-'A';
                height[y-'A']=height[x-'A']+1;
            }
            if(z!='-'){
                child[z-'A']=x-'A';
                height[z-'A']=height[x-'A']+1;
            }
        }
        for(int i=0;i<b;i++){
            cin>>x>>y;
            int tmp1=x-'A',tmp2=y-'A';
            bool flag=true;
            if(height[tmp1]>height[tmp2]){//保证tmp1在上
                swap(tmp1,tmp2);
                flag=false;
            }
            int k=find(tmp2,tmp1);
            if(k==0){
                cout<<'-'<<endl;
            }
            else{
                string res="";
                int tmp=k;
                while(k>2){
                    res+="great-";
                    k--;
                }              
                // if(tmp>2){
                //     res=res.substr(0,res.size()-1);
                // }
                if(k==2){
                    res+="grand";
                }
                if(flag){
                    res+="child";
                }
                else{
                    res+="parent";
                }
                cout<<res<<endl;
            }
        }
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务