团体程序设计天梯赛 决赛 L2-016. 愿天下有情人都是失散多年的兄妹

题目意思很清晰,就是找出五代以内是否有相同的祖先

可以创建一个结构,直接用结构数组进行判断

直接上代码,简单易懂。

#include<stdio.h>
typedef struct Node
{
	int sex;//0代表女,1代表男 
	int mother;
	int father;
}Node;
Node s[120000];
void init()
{
	int i;
	for(i=0;i<=120000;i++)
	{
		s[i].mother=s[i].father=-1;
	}
}
int Judge(int a,int b)
{
	int k,l;
	k=l=0;
	int r,t;
	r=t=0;
	int j,i;
	int p[10000];
	int o[10000];
	p[0]=a;
	o[0]=b;
	int e=4;
	while(e--)
	{
		for(i=0;i<=k;i++)
		{
			if(s[p[i]].mother!=-1)
				p[++r]=s[p[i]].mother;
			if(s[p[i]].father!=-1)
				p[++r]=s[p[i]].father;
		}
		k=r;
		for(i=0;i<=l;i++)
		{
			if(s[o[i]].mother!=-1)
				o[++t]=s[o[i]].mother;
			if(s[o[i]].father!=-1)
				o[++t]=s[o[i]].father;
		}
		l=t;	
	}
	for(i=0;i<=k;i++)
	{
		for(j=0;j<=l;j++)
		{
			if(p[i]==o[j])
				return 1;
		}
	}
	return 0;
}
int main()
{
	int n,i,j,k;
	scanf("%d",&n);
	int z,f,m;
	char x;
	init();
	while(n--)
	{
		scanf("%d %c%d%d",&z,&x,&f,&m);
		if(x=='F')
			s[z].sex=0;
		else if(x=='M')
			s[z].sex=1;
		s[z].mother=m;
		s[z].father=f;
		if(f!=-1)
			s[f].sex=1;
		if(m!=-1)
			s[m].sex=0; 
	}
	scanf("%d",&k);
	while(k--)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		if(s[a].sex==s[b].sex)
		{
			printf("Never Mind\n");
			continue;
		}
		int t=Judge(a,b);
		if(t==1)
			printf("No\n");
		else
			printf("Yes\n");
	}
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值