题解 | 找出直系亲属

#include<iostream>

using namespace std;
int f[26];
void init() {
    for (int i = 0; i < 50; i++) {
        f[i] = i;
    }
}
int find(int x) {
    if (x != f[x])return find(f[x]);
    return f[x];
}

int main() {
    int n, m;
    cin >> n >> m;
    string s;
    init();
    while (n--) {
        cin >> s;
        int a = s[0] - 'A';
        for (int i = 1; i < s.size(); i++) {
            if (s[i] == '-')continue;
            int t = s[i] - 'A';
            f[t] =  a;
        }
    }
    while (m--) {
        cin >> s;
        int a = s[0] - 'A', b = s[1] - 'A';
        int num = 0;
        int pl = a, ul = b; //先测试a为祖先,a——>b关系
        while (b != f[pl]) {
            if (pl == f[pl])break;
            pl = f[pl];
            num++;
        }
        if (b == f[pl]) { //a找到了b,b是a的后代
            num++;
            string str = "parent";
            if (num == 1)str = "parent";
            else if (num == 2)str = "grandparent";
            else {
                str = "grandparent";
                while (num != 2) {
                    str = "great-" + str;
                    num--;
                }
            }
            cout << str << endl;
        } else if (b != f[pl]) { //说明b在a前,b为a的祖先
            num = 0;
            while (a != f[ul]) {
                if (ul == f[ul])break;
                ul = f[ul];
                num++;
            }
            if (a == f[ul]) {
                num++;
                string str = "child";
                if (num == 1)str = "child";
                else if (num == 2)str = "grandchild";
                else {
                    str = "grandchild";
                    while (num != 2) {
                        str = "great-" + str;
                        num--;
                    }
                }
                cout << str << endl;
            }
        }
        if (b != f[pl] && a != f[ul]) {
            cout << "-" << endl;
            continue;
        }

    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
# 春招至今,你的战绩如何? #
13730次浏览 132人参与
# AI面会问哪些问题? #
813次浏览 19人参与
# MiniMax求职进展汇总 #
24614次浏览 313人参与
# 你的实习产出是真实的还是包装的? #
2431次浏览 47人参与
# AI时代,哪个岗位还有“活路” #
2495次浏览 49人参与
# 长得好看会提高面试通过率吗? #
2446次浏览 39人参与
# 米连集团26产品管培生项目 #
6871次浏览 223人参与
# 你做过最难的笔试是哪家公司 #
1020次浏览 18人参与
# HR最不可信的一句话是__ #
914次浏览 31人参与
# 沪漂/北漂你觉得哪个更苦? #
908次浏览 29人参与
# 军工所铁饭碗 vs 互联网高薪资,你会选谁 #
7898次浏览 43人参与
# XX请雇我工作 #
51120次浏览 171人参与
# 简历中的项目经历要怎么写? #
310766次浏览 4252人参与
# 简历第一个项目做什么 #
31981次浏览 354人参与
# 不考虑薪资和职业,你最想做什么工作呢? #
152726次浏览 888人参与
# 当下环境,你会继续卷互联网,还是看其他行业机会 #
187486次浏览 1123人参与
# AI时代,哪些岗位最容易被淘汰 #
64398次浏览 857人参与
# 如果重来一次你还会读研吗 #
229937次浏览 2011人参与
# 正在春招的你,也参与了去年秋招吗? #
364032次浏览 2640人参与
# 腾讯音乐求职进展汇总 #
160794次浏览 1114人参与
# 你怎么看待AI面试 #
180527次浏览 1287人参与
# 投格力的你,拿到offer了吗? #
178044次浏览 889人参与
牛客网
牛客网在线编程
牛客网题解
牛客企业服务