题解 | #找出直系亲属#

找出直系亲属

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;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-29 17:30
找实习找着找着就要进入7月了,马上秋招也要开始了,找实习还有意义吗?
绝迹的星:有面就面, 没面上就当日薪4位数大佬免费培训, 面上了再考虑要不要实习
点赞 评论 收藏
分享
点赞 评论 收藏
分享
05-26 22:25
门头沟学院 Java
Java小肖:不会是想叫你过去把你打一顿吧,哈哈哈
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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