每日一九度之 题目1035:找出直系亲属

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:2639

解决:1050

题目描述:
    如果A,B是C的父母亲,则A,B是C的parent,C是A,B的child,如果A,B是C的(外)祖父,祖母,则A,B是C的 grandparent,C是A,B的grandchild,如果A,B是C的(外)曾祖父,曾祖母,则A,B是C的great- grandparent,C是A,B的great-grandchild,之后再多一辈,则在关系上加一个great-。
输入:
    输入包含多组测试用例,每组用例首先包含2个整数n(0<=n<=26)和m(0<m<50), 分别表示有n个亲属关系和m个问题, 然后接下来是n行的形式如ABC的字符串,表示A的父母亲分别是B和C,如果A的父母亲信息不全,则用-代替,例如A-C,再然后是m行形式如FA的字符 串,表示询问F和A的关系。
    当n和m为0时结束输入。
输出:
    如果询问的2个人是直系亲属,请按题目描述输出2者的关系,如果没有直系关系,请输出-。
    具体含义和输出格式参见样例.
样例输入:
3 2
ABC
CDE
EFG
FA
BE
0 0
样例输出:
great-grandparent
-

家谱树,也算是是数组的活用吧!自己还是缺乏思考啊

//Asimple
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <stack>
#include <cmath>
#include <map>
#include <string>
#include <queue>
#define INF 100000
using namespace std;
const int maxn = 35;
typedef long long ll;
int n, m;
char str[5];
int fa[maxn];

int find_f(int x, int y){
    int r = 1;
    while( fa[x] != -1 ){
        if( fa[x] == y ) return r;
        x = fa[x];
        r ++;
    }
    return -1;
}

int main(){
    while( scanf("%d %d",&n,&m) && ( n + m ) ){
        for(int i=0; i<maxn; i++){
            fa[i] = -1;
        } 
        while( n -- ){
            scanf("%s",str);
            fa[str[1]-'A'] = fa[str[2]-'A'] = str[0]-'A';
        }
        while( m -- ){
            scanf("%s",str);
            int x = find_f(str[0]-'A',str[1]-'A');
            int y = find_f(str[1]-'A',str[0]-'A');
            int r = max(x, y);
            if( r <= 0 ){
                printf("-\n");
            } else {
                if( x > 0 ){
                    if( r == 1 ) printf("parent\n");
                    else {
                        for(int i=2; i<r; i++){
                            printf("great-");
                        }
                        printf("grandparent\n");
                    }
                } else if( y > 0){
                    if( r == 1 ) printf("child\n");
                    else{
                        for(int i=2; i<r; i++){
                            printf("great-");
                        }
                        printf("grandchild\n");
                    }
                }
            }
        }
    }
    return 0;
}

 

posted @ 2016-09-18 15:34  Asimple  阅读(261)  评论(0编辑  收藏  举报