Family Tree 题解

题面:

在这里插入图片描述

翻译:

农夫想要研究他的农场中的奶牛的血缘关系.

输入:

第一行是一个数字n和要研究的两头奶牛的名字a和b.
然后n行,一些奶牛之间的关系
每行有两个名字,前面的名字是后面的名字的母亲.

输出:

输出a和b的关系.

  • 如果他们是姐妹,输出"SIBLINGS"
  • 如果他们是直系亲属(图中的mother系列),那么输出他们的关系.
  • 如果他们是旁系亲属(图中的anut系列),那么输出他们的关系.
  • 如果他们关系aunt系列还要远(图中的cousin系列),俺么输出"COUSINS".
  • 如果他们没有关系,那么输出"NOT RELATED".

题目分析:

我们用两个数组mother和daughter来记录每一对给出的关系(mother[i]是daughter[i]的母亲).
然后用比较暴力的方式找到a和b的最近的共同祖先(具体代码很容易懂)
用fara和farb分别记录他们和最近祖先的距离.
近的为前辈,远的为晚辈(输出是时候格式是前辈是晚辈的XXXX)
如果能找到,那么他们有关系
然后在按照fara和farb确定关系并且输出结果.

代码:

#include<bits/stdc++.h>

using namespace std;

string mother[150];
string daughter[150];
string a, b, amother ,bmother;

int n, fara, farb;
bool isR;

string getMother(string da){
    for(int i = 0; i < n; i++){
        if(daughter[i] == da){
            return mother[i];
        }
    }
    return "";
}

int main(){
    scanf("%d", &n);
    cin>>a>>b;
    for(int i = 0; i < n; ++i)  cin>>mother[i]>>daughter[i];
    amother = a;

    
    //这里是在找最近的共同祖先
    while(amother != ""){
        farb = 0;
        bmother = b;
        while(bmother != ""){
            if(bmother == amother){
                isR = 1;
                break;
            }
            bmother = getMother(bmother);
            farb++;
        }
        if(isR){
            break;
        }
        amother = getMother(amother);
        fara++;
    }
    //确定关系
    if(isR){
        if(fara > 1 && farb > 1){
            cout << "COUSINS" << endl;
        }else if(fara == 1 && farb == 1){
            cout << "SIBLINGS" << endl;
        }else{
            if(fara > farb){
                cout << b << " is the ";
                while(fara > 2){
                    cout << "great-";
                    fara--;
                }
                if(fara == 2 && farb == 0){
                    cout << "grand-mother of " << a << endl;
                }else if(fara == 2 && farb == 1){
                    cout << "aunt of " << a << endl;
                }else if(fara == 1){
                    cout << "mother of " << a << endl;
                }
            }else{
                cout << a << " is the ";
                while(farb > 2){
                    cout << "great-";
                    farb--;
                }
                if(farb == 2 && fara == 0){
                    cout << "grand-mother of " << b << endl;
                }else if(farb == 2 && fara == 1){
                    cout << "aunt of " << b << endl;
                }else if(farb == 1){
                    cout << "mother of " << b << endl;
                }
            }
        }
    }else{
        cout << "NOT RELATED" << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_25807093/article/details/88584314