1118 Birds in Forest

98 篇文章 0 订阅
8 篇文章 0 订阅

在这里插入图片描述在这里插入图片描述

题目大意:

有n张照片,每张上面的鸟来自同一棵树,问有多少棵树和鸟,并且查询一对鸟是否来自同一棵树。

解题思路:

并查集板子题,合并每一对输入的鸟,用数组记录鸟的编号并统计鸟的数量,最后用father数组统计树的数量。
代码如下:

#include<iostream>
#include<cstdio>
#include<set>
#include<algorithm>
using namespace std;
int father[11000],book[11000],n,q;
int getf(int f)//一开始用递归写法有一个3分测试点超时了 
{
	int a=f;
	while(f!=father[f])
	{
		f=father[f];
	}
	while(a!=father[a])
	{
		int z=a;
		a=father[a];
		father[z]=f;
	}
	return f;
}
void merge(int a,int b)
{
  int fa=getf(a);
  int fb=getf(b);
  if(fa!=fb)
  {
  	father[fb]=fa;
  }	
}
void init()//预处理father数组 
{
	for(int i=1;i<=10000;i++)
	 father[i]=i;
}
int main()
{
	init();
	scanf("%d",&n);
	int num1=0,num2=0;
	for(int i=1;i<=n;i++)
	{
		int t,tmp[1100]={0};
		scanf("%d",&t);
		for(int j=0;j<t;j++)
		{
			scanf("%d",&tmp[j]);
			if(book[tmp[j]]==0)
			{
				num2++;//鸟的数量 
				book[tmp[j]]=1;
			}
			if(j!=0)
				merge(tmp[j-1],tmp[j]);
		 } 
	}
	for(int i=1;i<=num2;i++)//统计树的数量 
	{
		if(book[i]&&father[i]==i)num1++;
	}
	scanf("%d",&q);
	printf("%d %d\n",num1,num2);
	while(q--)
	{
		int a,b;
		scanf("%d %d",&a,&b);
		if(getf(a)==getf(b))printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值