题解 | #找出直系亲属#

找出直系亲属

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

并查集

#include <iostream>
#include <vector>
#include <string>
using namespace std;
 
void Union(vector<int>& s, int a, int b) {       //ABC 将A看作B和C的父结点
    s[b] = a;
}

int Find(vector<int>& s, int a, int b) {
    int cnt = 0;
    while (s[a] >= 0) {
        cnt++;
        if (s[a] == b) return cnt;
        a = s[a];
    }
    return 0;
}

int main()       //整个数据结构像翻转过来的二叉树
{
    int n, m;
    cin >> n;
    cin >> m;
    vector<int> s(26, -1);
    getchar();
    while (n--) {
        string str;
        getline(cin, str);
        if (str[1] != '-') Union(s, str[0] - 'A', str[1] - 'A');
        if (str[2] != '-') Union(s, str[0] - 'A', str[2] - 'A');        
    }
    while (m--) {
        string str;
        getline(cin, str);
        int cnt1 = Find(s, str[0] - 'A', str[1] - 'A');
        if (cnt1 > 0) {
            if (cnt1 == 1) {
                cout << "parent" << endl;
                continue;
            }
            if (cnt1 == 2) {
                cout << "grandparent" << endl;
                continue;
            }
            string res = "grandparent";
            cnt1 = cnt1 - 2;
            while (cnt1--) {
                res = "great-" + res;
            }
            cout << res << endl;
            continue;
        }
        int cnt2 = Find(s, str[1] - 'A', str[0] - 'A');
        if (cnt2 > 0) {
            if (cnt2 == 1) {
                cout << "child" << endl;
                continue;
            }
            if (cnt2 == 2) {
                cout << "grandchild" << endl;
                continue;
            }
            string res = "grandchild";
            cnt2 = cnt2 - 2;
            while (cnt2--) {
                res = "great-" + res;
            }
            cout << res << endl;
            continue;
        }
        if (cnt1 == 0 && cnt2 == 0) cout << "-" << endl;
    }
    return 0;
}
全部评论

相关推荐

牛客60022193...:大厂都招前端,他们觉得AI能替代前端,可能他们公司吊打btaj吧
点赞 评论 收藏
分享
10-19 11:19
已编辑
哈尔滨理工大学 golang
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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