找出直系亲属
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1681 Accepted Submission(s): 681
Problem Description
如果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-。
Input
输入包含多组测试用例,每组用例首先包含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时结束输入。
当n和m为0时结束输入。
Output
如果询问的2个人是直系亲属,请按题目描述输出2者的关系,如果没有直系关系,请输出-。
具体含义和输出格式参见样例.
具体含义和输出格式参见样例.
Sample Input
3 2 ABC CDE EFG FA BE 0 0
Sample Output
great-grandparent -
Source
这道题就是构造一颗二叉树,从给出的第一个节点遍历看是否为另一个节点的子节点,或者父节点,如果是相差多少层。在训练赛的时候想到了这种思想,也知道用DFS,但就是做不出来,还是做这种题做少了,离比赛越来越近了,抓紧时间吧。
#include <iostream>
#include<cstdio>
#include<cstring>
#define N 30
using namespace std;
int cnt;
int n,m;
struct node
{
int mother,father;
}a[N];
//从x开始往后遍历找y
void dfs(int k,int x,int y)
{
if(x==y)
{
cnt=k;
return;
}
if(a[x].mother!=-1)
{
dfs(k+1,a[x].mother,y);
}
if(a[x].father!=-1)
{
dfs(k+1,a[x].father,y);
}
}
int main()
{
char str1[3],str2[2];
while(~scanf("%d%d",&n,&m))
{
if(n==0&&m==0) break;
memset(a,-1,sizeof(a));
for(int i=0;i<n;i++)
{
scanf("%s",str1);
if(str1[1]!='-') a[str1[0]-'A'].father=str1[1]-'A';
if(str1[2]!='-') a[str1[0]-'A'].mother=str1[2]-'A';
}
while(m--)
{
scanf("%s",str2);
int b=str2[0]-'A';
int c=str2[1]-'A';
cnt=0;
dfs(0,b,c);
if(cnt==1)
{
printf("child\n");
continue;
}else if(cnt==2)
{
printf("grandchild\n");
continue;
}
else if(cnt>2)
{
for(int i=0;i<cnt-2;i++)
{
printf("great-");
}
printf("grandchild\n");
continue;
}
dfs(0,c,b);
if(cnt==1)
{
printf("parent\n");
continue;
}else if(cnt==2)
{
printf("grandparent\n");
continue;
}
else if(cnt>2)
{
for(int i=0;i<cnt-2;i++)
{
printf("great-");
}
printf("grandparent\n");
continue;
}
printf("-\n");
}
}
return 0;
}