一.题目描述:
如果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
-
二.题目分析.
调了半天,终于AC了。。但是看完题解,瞬间被自己蠢哭了,总是这么不机智可怎么好。。。B,C是A的双亲,所以A的孩子是C,B的孩子是C,完美的单射关系,从双亲找孩子匹配,就是强大并查集应用,太完美了。我却从孩子匹配双亲,A的双亲是C,B,非要搞成一对多映射,从孩子找双亲,每次要考虑两个双亲。其实第一眼看到时候,感觉和并查集很像,但是想到两个双亲,没办法映射,于是又放弃了,有时候就是一瞬间灵活的问题,但愿我慢慢机智起来!
三.代码
1.递归
#include <stdio.h>
#include <stdlib.h>
//0<=n<=26 0<m<50
int m,n,a[26][2];
int ans=-1;
void search(int child,int parent,int cn)
{
if(a[child][0]==-1&&a[child][1]==-1)
return;
if(a[child][0]==parent||a[child][1]==parent)
{
ans=cn;
return ;
}
if(a[child][0]!=-1)
search(a[child][0],parent,cn+1);
if(a[child][1]!=-1)
search(a[child][1],parent,cn+1);
return ;
}
int main()
{
int i,j;
char str[3];
freopen("1035.txt","r",stdin);
while(scanf("%d%d",&n,&m)&&n&&m)
{
for(i=0;i<26;i++)
{
a[i][0]=-1; //存双亲的号码
a[i][1]=-1;
}
for(i=0;i<n;i++)
{
scanf("%s",str);
if(str[1]!='-')
a[str[0]-'A'][0]=str[1]-'A';
if(str[2]!='-')
a[str[0]-'A'][1]=str[2]-'A';
}
for(i=0;i<m;i++)
{
scanf("%s",str);
ans=-1;
if(a[str[0]-'A'][0]==-1&&a[str[0]-'A'][1]==-1)
{
search(str[1]-'A',str[0]-'A',0); //child
if(ans==-1)
{
printf("-\n");
continue;
}
while(ans>1)
{
printf("great-");
ans--;
}
printf("grandparent\n");
}
else //parent
{
search(str[0]-'A',str[1]-'A',0);
if(ans==-1)
{
printf("-\n");
continue;
}
while(ans>1)
{
printf("great-");
ans--;
}
printf("grandchild\n");
}
}
}
return 0;
}
2.并查集
#include<iostream>
using namespace std;
int tree[1001]; //孩子节点
int relation(int a, int b) { //计算层差以确定关系
int t = 1;
while (tree[a] != -1) {
if (tree[a] == b)
return t;
a = tree[a];
++t;
}
return -1;
}
int main()
{
int n, m;
while (cin >> n >> m && n && m) {
for (int i=0; i!=1000; ++i)
tree[i] = -1;
string s;
int a, b, c;
while (n--) {
cin >> s;
a = s[0] - 'A';
b = s[1] - 'A';
c = s[2] - 'A';
tree[b] = tree[c] = a; //
}
while (m--) {
cin >> s;
a = relation(s[0]-'A', s[1]-'A'); //a>0,前者为父母
b = relation(s[1]-'A', s[0]-'A');
int t = a>b?a:b; //t为层差
if (t <= 0)
cout << "-" << endl;
else {
while (t > 2) {
cout << "great-";
--t;
}
if (t == 2) {
cout << "grand";
--t;
}
if (t == 1) {
if (a > 0)
cout << "parent" << endl;
else
cout << "child" << endl;
}
}//else
}//while m
}
return 0;
}