1050: 找出直系亲属
时间限制: 1 Sec 内存限制: 128 MB提交: 72 解决: 61
[ 提交][ 状态][ 讨论版]
题目描述
如果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时结束输入。
当n和m为0时结束输入。
输出
如果询问的2个人是直系亲属,请按题目描述输出2者的关系,如果没有直系关系,请输出-。
具体含义和输出格式参见样例.
具体含义和输出格式参见样例.
样例输入
3 2
ABC
CDE
EFG
FA
BE
0 0
样例输出
great-grandparent-
采用递归的思想(我师父的代码嘻嘻)
#include<iostream> using namespace std; int find(char relation[][4],int n,char begin,char end) { int i; for(i=0;i!=n;i++) { if(relation[i][0]==begin) break; } if(i==n) return -999; if(relation[i][1]==end||relation[i][2]==end) return 1; else{ int a=find(relation,n,relation[i][1],end); int b=find(relation,n,relation[i][2],end); return 1+(a>=b?a:b); } } int main() { int n,m; while(cin>>n>>m) { if(n==0&&m==0) break; char relation[n][4]; for(int i=0;i!=n;i++) cin>>relation[i]; while(m--) { char question[3]; cin>>question; int generation; if((generation=find(relation,n,question[0],question[1]))>0) { if(generation==1) cout<<"child"<<endl; else{ for(int i=1;i<=generation-2;i++) cout<<"great-"; cout<<"grandchild"<<endl; } }else if((generation=find(relation,n,question[1],question[0]))>0) { if(generation==1) cout<<"parent"<<endl; else{ for(int i=1;i<=generation-2;i++) cout<<"great-"; cout<<"grandparent"<<endl; } }else cout<<"-"<<endl; } } return 0; }