HDU 3786 找出直系亲属 -- DFS

HDU 3786 找出直系亲属  -- DFS


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 224    Accepted Submission(s): 94


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时结束输入。
 

Output
如果询问的2个人是直系亲属,请按题目描述输出2者的关系,如果没有直系关系,请输出-。
具体含义和输出格式参见样例.
 

Sample Input
  
  
3 2
ABC
CDE
EFG
FA
BE
0 0
 

Sample Output
  
  
great-grandparent
-
 

Source
 

分析:
建立一个从A到Z 26个节点的结构体数组。DFS 深度优先搜索
如果每对父母可以有多个子女,就不能用此结构来做了。

代码如下:
#include <iostream>
using namespace std;

struct Node
{
	Node *father;
	Node *mother;
	Node *child;
	Node(){father=0;mother=0;child=0;}
}*people;

int findParentRelative(Node *a,Node *b)
{
	//cout<<"findParentRelative Function"<<endl;
	if(a==NULL)return 0;
	int g=0;
	if(a==b)return 1;
	g = findParentRelative(a->father,b);
	if(g>0){return g+1;}
	g = findParentRelative(a->mother,b);
	if(g>0){return g+1;}
	return 0;
}

int findChildRelative(Node *a,Node *b)
{
	//cout<<"findChildRelative Function"<<endl;
	if(a==NULL)return 0;
	int g=0;
	if(a==b)return -1;
	g = findChildRelative(a->child,b);
	if(g<0){return g-1;}
	return 0;
}

void print(int n)
{
	//cout<<"n:"<<n<<endl;
	if(n==1 || n==-1){cout<<"-"<<endl;return;}
	if(n==2){cout<<"child"<<endl;return;}
	if(n==-2){cout<<"parent"<<endl;return;}
	for(int i=0;i<abs(n)-3;i++)
	{
		cout<<"great-";
	}
	if(n>0){cout<<"grandchild"<<endl;return;}
	else {cout<<"grandparent"<<endl;return;}
	return;
}

int main()
{
	int n,m;
	people= (Node *)malloc(sizeof(Node)*26);
	char r[5];
	int i,t,gener=0;
	while(1)
	{
		cin>>n>>m;
		if(n==0 && m==0)break;
		memset(people,0,sizeof(Node)*26);
		for(i=0;i<n;i++)
		{
			cin>>r;
			t = r[0]-'A'; 
			if(r[1]!='-')
			{
				people[t].father=&people[r[1]-'A'];         //这里注意要有 ‘&’
				people[r[1]-'A'].child = &people[t];
			}
			if(r[2]!='-')
			{
				people[t].mother=&people[r[2]-'A'];
				people[r[2]-'A'].child = &people[t];
			}
		}
		//cout<<"begin to input question:"<<m<<endl;
		for(i=0;i<m;i++)
		{
			cin>>r;	
			//cout<<"r:"<<r<<endl;
			gener = findParentRelative(&people[r[0]-'A'],&people[r[1]-'A']);
			if(gener>0){print(gener);}
			else 
			{
				gener = findChildRelative(&people[r[0]-'A'],&people[r[1]-'A']);
				if(gener<0){print(gener);}
				else cout<<"-"<<endl;
			}
		//	cout<<"Generation:"<<gener<<endl;
		}
	
	}

	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值