题解 | #找出直系亲属#

找出直系亲属

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

#include "bits/stdc++.h"

using namespace std;


class UnionSet{
public:
    int us[27];

    UnionSet() {
        memset(us,-1, sizeof(int)*27);
    }

    // 子女关系返回1,非直系返回-1,询问n1是n2的谁
    int find(char n1,char n2)
    {
        int node1=n1-'A';
        int node2=n2-'A';

        for (int i = node1,k=0; i>=0; i=us[i],k++) {
            if (i==node2)
            {
                return k;
            }
        }

        for (int i = node2,k=0; i>=0; ++k,i=us[i]) {
            if (i==node1)
                return -k;
        }

        return 0;
    }

    void setParent(string str)
    {
       int child=str[0]-'A';
       int parent1=(str[1]!='-' ? str[1]-'A' : -1);
       int parent2=(str[2]!='-' ? str[2]-'A' : -1);
        if (parent1!=-1)
            us[parent1]=child;
        if (parent2!=-1)
            us[parent2]=child;
    }
    string getRelationName(int n)
    {
        if (n==0)
        {
            return "-";
        }
        if (abs(n)==1)
        {
            return n==1 ? "parent":"child";
        }

        string ans= (n > 0 ? "grandparent" : "grandchild");

        while (abs(n)>2)
        {
            ans="great-"+ans;
            n>0 ? n-- : n++;
        }
        return ans;
    }

};
int main()
{
    int n,m;
    while (cin>>n>>m)
    {
        vector<string> input(n);
        UnionSet set;
        for (int i = 0; i < n; ++i) {
            cin>>input[i];
            set.setParent(input[i]);
        }

        vector<string> questions(m);
        for (int i = 0; i < m; ++i) {
            cin>>questions[i];

        }

        for (string question: questions) {
            cout<<set.getRelationName(set.find(question[0],question[1]))<<endl;
        }


    }


}

全部评论

相关推荐

大猪蹄子哥:1-谁教你这么写教育经历的……咱都这个学历了,很多公司要看本科、硕士,Gap Year的,你啪就给一个上大26届硕士,没了。 2-那堆奖学金揉成一行放最后得了,放前面显得你没技术自信,还是那句话,对于咱这个学历直接上重点,你这上半段看起来像个大专(无恶意 3-专业技能最好点出来细化方向,你熟悉的以太网是UDP还是TCP,是千兆还是万兆等等,多种信号处理……那你倒是说两个啊,后面空着干嘛,会的干嘛不讲 4-项目经历废话太多,描述不专业(怎么还有我,我们这种词),没有数据支撑(是婴儿还是巨人看不出来)。最后如果这些是真的XX项目、比赛,最好点出来,不然更显得像自学着玩的,或者说抄的(经典复现等于我做过 5-个人总结在咱这个分段没用
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务