九度[1035]-找出直系亲属
2017-09-06 21:57
295 查看
九度[1035]-找出直系亲属
题目描述:如果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代码:
#include <cstdio> #include <map> #include <iostream> using namespace std; const int maxn = 100; int n, m; map<string, string> father, mother; void print(int x, int type){ if(type == 1){ if(x == 1) printf("parent\n"); else if(x == 2) printf("grandparent\n"); else if( x > 2){ string s0 = "grandparent", str = "great-"; for(int i = 0; i < x-2; i++){ s0.insert(0, str); } cout<<s0<<endl; } else return; } else{ if(x == 1) printf("child\n"); else if(x == 2) printf("grandchild\n"); else if( x > 2){ string s0 = "grandchild", str = "great-"; for(int i = 0; i < x-2; i++){ s0.insert(0, str); } cout<<s0<<endl; } else return; } } int find(string child, string parent){ int num = -1; if(father.count(child) == 0 && mother.count(child) == 0) return num; else num = 1; if(father[child] != parent && mother[child] != parent){ int plus = find(father[child], parent); if(plus == -1) plus = find(mother[child], parent); if(plus == -1) return -1; else num += plus; } return num; } int main(){ freopen("C:\\Users\\Administrator\\Desktop\\test.txt", "r", stdin); while(scanf("%d%d", &n, &m) != EOF){ if(n == 0 && m == 0) break; string family; for(int i = 0; i < n; i++){ cin>>family; if(family[1] != '-') father[family.substr(0, 1)] = family.substr(1, 1); if(family[2] != '-') mother[family.substr(0, 1)] = family.substr(2, 1); } string query; for(int i = 0; i < m ; i++){ cin>>query; int a = find(query.substr(1,1), query.substr(0,1)); int b = find(query.substr(0,1), query.substr(1,1)); if(a == -1 && b == -1) printf("-\n"); else{ print(a, 1); print(b, 2); } } father.clear(); mother.clear(); } fclose(stdin); return 0; }
相关文章推荐
- 九度OJ 1035找出直系亲属
- 九度OJ 1035:找出直系亲属 (二叉树、递归)
- 九度OJ 1035:找出直系亲属 (二叉树、递归)
- 九度oj 题目1035:找出直系亲属 【ZJU2009考研机试题5】
- 【九度OJ】题目1035:找出直系亲属
- 九度1035 -树 - 找出直系亲属
- 九度OJ 1035 找出直系亲属
- 九度OJ题目1035:找出直系亲属
- 九度OJ题目1035:找出直系亲属
- 九度OJ-题目1035 找出直系亲属
- 九度1035:找出直系亲属<并查集>
- 九度OJ 1035:找出直系亲属(二叉树)
- [Jobdu] 题目1035:找出直系亲属
- 题目1035:找出直系亲属
- 题目1035:找出直系亲属
- OJ_1035 找出直系亲属
- 题目1035:找出直系亲属
- 题目1035:找出直系亲属
- 题目1035:找出直系亲属 树
- 题目1035:找出直系亲属