-
题目描述:
-
如果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
这个题目第一眼看上去很像并查集,但是仔细分析可以发现,这个题目是利用已知条件构造森林然后对其中的关系进行查找。
题目的第一行的两个输入分别是所有的information的个数,第二个输入是所有的quest的个数。
接下来的几行是information,以ABC为例,B为A的parent,C为A的parent。根据这个关系,我们可以想到建立树的方法:利用一维的数组存储,然后数组中存放数组下标对应的子孙所在位置。那么可以想到用stl中的map容器进行处理。
把森林(树)构造完毕后,我们对所有的quest进行查询。很自然就是顺着child这个内容进行查找。下面函数的find就是实现这个功能。
PS:有一种很简单的检测程序对错的测试办法,记着二叉树了没?
#include<iostream>
#include<map>
#include<string>
#include<string.h>
using namespace std;
map<char,int> temp;
map<char,int>::iterator it;
struct node{
char id;
int child;
};
node rel[100];
int find(int x,int y)
{
int count=0;
while(x!=y&&x!=0)
{
count=count+1;
x=rel[x].child;
}
if(x==0)
return 0;
else return count;
}
int main()
{
int n,m,count,i,tra1,tra2,tra3;
char a,b,c;
while(cin>>n>>m)
{
if(n==0&&m==0)
break;
count=0;
if(!temp.empty())
temp.clear();
for(i=1;i<100;i++)
rel[i].child=0;
for(i=1;i<=n;i++)
{
cin>>a>>b>>c;
it=temp.find(a);
if(a!='-'&&it==temp.end())
temp.insert(pair<char,int>(a,++count));
it=temp.find(b);
if(b!='-'&&it==temp.end())
temp.insert(pair<char,int>(b,++count));
it=temp.find(c);
if(c!='-'&&it==temp.end())
temp.insert(pair<char,int>(c,++count));
if(a!='-')
tra1=temp[a];
if(b!='-'&&a!='-')
{
tra2=temp[b];
rel[tra2].child=tra1;
}
if(c!='-'&&a!='-')
{
tra3=temp[c];
rel[tra3].child=tra1;
}
}
for(i=1;i<=m;i++)
{
cin>>a>>b;
if(a=='-'||b=='-')
cout<<"-"<<endl;
else {
int tra1,tra2,count1,count2;
tra1=temp[a];
tra2=temp[b];
count1=find(tra1,tra2);
count2=find(tra2,tra1);
if(count1==0&&count2==0)
cout<<"-"<<endl;
else if(count1>0)
{
while(count1>=3)
{
cout<<"great-";
count1=count1-1;
}
while(count1>=2)
{
cout<<"grand";
count1=count1-1;
}
cout<<"parent"<<endl;
}
else if(count2>0)
{
while(count2>=3)
{
cout<<"great-";
count2=count2-1;
}
while(count2>=2)
{
cout<<"grand";
count2=count2-1;
}
cout<<"child"<<endl;
}
}
}
}
return 0;
}