天梯题集——愿天下有情人都是失散多年的兄妹(隐藏条件)

愿天下有情人都是失散多年的兄妹

t1
t2

解题思路

利用结构体读入每个 ID 下数据
隐藏条件:标记父母的性别 (卡死个人)

假设判断 a,b 是否可通婚
同性输出 “Never Mind”
不同性 bfs标记 a 的五代内的祖先 check检查 b 五代内的祖先
			b 五代内的祖先被标记过 输出“No”
			b 五代内的祖先全部未被标记过 输出“Yes”
#include<bits/stdc++.h>
using namespace std;
bool judge[100010];
int flag;
struct node{
	int fa, ma;
	char sex;
}num[100010];

void bfs(int a, bool *judge, int k){
	if(k==5) return;
	int x = num[a].fa;
	int y = num[a].ma;
	if(x!=0&&x!=-1){
		judge[x]=true;
		bfs(x, judge, k+1);
	}
	if(y!=0&&y!=-1){
		judge[y]=true;
		bfs(y, judge, k+1);
	}
	return ;
}

void check(int a, bool *judge, int k){
	if(k==5||flag) return;
	int x = num[a].fa;
	int y = num[a].ma;
	if(x!=-1&&x!=0){
		if(judge[x]){
			flag=1;
			return;
		}
		else
			check(x, judge, k+1);
	}
	if(y!=-1&&y!=0){
		if(judge[y]){
			flag=1;
			return;
		}
		else
			check(y, judge, k+1);
	}
	
	return ;
}

int main(){
	int n;
	cin>>n;
	for(int i=0; i<n; i++){
		int index;
		cin>>index;
		cin>>num[index].sex>>num[index].fa>>num[index].ma;
		num[num[index].fa].sex = 'M';
		num[num[index].ma].sex = 'F';
	}
	int k;
	cin>>k;
	for(int i=0; i<k; i++){
		int a, b;
		flag=0;
		cin>>a>>b;
		if(num[a].sex==num[b].sex){
			cout<<"Never Mind\n";
		}	
		else{
			memset(judge, false, sizeof(judge));
			bfs(a, judge, 1);
			check(b, judge, 1);
			if(!flag)
				cout<<"Yes\n";
			else
				cout<<"No\n";
		}
	}
	
	return 0;
} 

总结

一开始没标记父母性别,想来想去都不知道哪里的问题。
题目中的隐藏条件,再一次说明细节真的很重要。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值