找出直系亲属
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 290 Accepted Submission(s): 123
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
Recommend
notonlysuccess
//Floyd算法
//这题用了Floyd算法,只要两点相通就有解!
//开始把map[x][y]和map[y][x]输出的项搞相反了,一直都没有发现!wa了n次,最后才发现,可花费了好
//多时间,以后一定要细心!
//Floyd算法
//这题用了Floyd算法,只要两点相通就有解!
//开始把map[x][y]和map[y][x]输出的项搞相反了,一直都没有发现!wa了n次,最后才发现,可花费了好
//多时间,以后一定要细心!
#include <iostream>
#include <cstdio>#include <cstring>
#include <cstdlib>
using namespace std;
#define MAX 26
int map[MAX][MAX];
int main()
{
int i, j, k, n, m;
char str[5];
while(true) {
cin>>n>>m;
if(0 == n && 0 == m) break;
memset(map, 0, sizeof(map));
for(i = 0; i < n; i++) {
cin>>str;
if(str[1] != '-') map[str[0]-'A'][str[1]-'A'] = 1;
if(str[2] != '-') map[str[0]-'A'][str[2]-'A'] = 1;
}
for(k = 0; k < MAX; k++) {
for(i = 0; i < MAX; i++)
for(j = 0; j < MAX; j++) {
if(map[i][k] && map[k][j]) {
map[i][j] = map[i][k] + map[k][j];
}
}
}
for(i = 0; i < m; i++ ) {
cin>>str;
int x = str[0] - 'A';
int y = str[1] - 'A';
//cout<<map[x][y]<<' '<<map[y][x]<<endl;
if(map[x][y]) {
if(map[x][y] > 1) {
for(j = map[x][y]; j > 2; j--)
cout<<"great-";
cout<<"grandchild"<<endl;
} else {
cout<<"child"<<endl;
}
}
else if(map[y][x]) {
if(map[y][x] > 1) {
for(j = map[y][x]; j > 2; j--)
cout<<"great-";
cout<<"grandparent"<<endl;
} else {
cout<<"parent"<<endl;
}
} else {
cout<<"-"<<endl;
}
}
}
return 0;}
[ Copy to Clipboard ] [ Save to File]