您的位置:首页 > 其它

OJ_1035 找出直系亲属

2014-02-16 09:04 232 查看
#include <iostream>
using namespace std;
typedef struct node{
char ch;
}node;

string getChild(int n)
{
string result;
if(n==-1)result="-";
else
if(n==1) result="child";
else
if(n==2) result= "grandchild";
else{
n-=2;
string pre="";
while(n--){
pre+="great-";
}
result=pre+"grandchild";
}

return result;
}
string getParent(int n)
{
string result;
if(n==-1)result="-";
else
if(n==1) result="parent";
else
if(n==2) result= "grandparent";
else{
n-=2;
string pre="";
while(n--){
pre+="great-";
}
result=pre+"grandparent";
}

return result;
}
int getRelation(node n[],char a,char b)
{
int i=0;
char t=a;
while(n[t].ch!='-'){
i++;
if(n[t].ch==b)return i;
t=n[t].ch;
}
return -1;
}
void func()
{
int n,m;
while(cin>>n>>m)
{
node nod[129];
for(int i=0;i<129;i++)
nod[i].ch='-';
if(n==0&&m==0)break;
for(int i=0;i<n;i++)
{
string temp;
cin>>temp;

nod[temp[1]].ch=temp[0];
nod[temp[2]].ch=temp[0];
}
for(int j=0;j<m;j++)
{
string str;
cin>>str;
int sum=getRelation(nod,str[0],str[1]);
if(sum>0)cout<<getParent(sum)<<endl;
else    {
sum=getRelation(nod,str[1],str[0]);
cout<<getChild(sum)<<endl;
}
}
}

}
int main(int argc, char *argv[])
{
//printf("Hello, world\n");
func();
return 0;
}


静态树(或并查集,不进行路径压缩),顺序找出二者层次关系,找不到则反序再找

题目描述:
如果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
-
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: