【数据结构 | C++】部落

在一个社区里,每个人都有自己的小圈子,还可能同时属于很多不同的朋友圈。我们认为朋友的朋友都算在一个部落里,于是要请你统计一下,在一个给定社区中,到底有多少个互不相交的部落?并且检查任意两个人是否属于同一个部落。

输入样例:

4

3 10 1 2

2 3 4

4 1 5 7 8

3 9 6 4

2

10 5

3 7

输出样例:

10 2

Y

N

c 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N=11000;
int a[N];
int find(int x)
{
	return a[x]==x?x:a[x]=find(a[x]);
}
void merge(int x,int y)
{
	int t1=find(x);
	int t2=find(y);
	if(t1!=t2)
	{
		a[t2]=t1;
	}
}
int main()
{
	int u=0;
	int cnt=0;
	queue<char > q; 
	set<int > s;
	int n,i,m;
	cin>>n;
	for(i=1;i<=10000;i++)
	{
		a[i]=i;
	}
	while(n--)
	{
		int t,x,y;
		cin>>t;
		if(t!=0)
		{
			cin>>x;
			if(u<x)
			{
				u=x;
			}
			s.insert(x);
			for(i=1;i<t;i++)
			{
				cin>>y;
				if(u<y)  
				{
					u=y;
				}
				merge(x,y); 
				s.insert(y); 
			}
		}
	}
	cin>>m;
	while(m--)
	{
		int x,y;
		cin>>x>>y;
		if(find(x)==find(y))
		{
			q.push('Y');
		}
		else
		{
			q.push('N');
		}
	}
	for(i=1;i<=u;i++)
	{
		if(a[i]==i)
		{
			cnt++;
		}
	}
	cout<<s.size()<<" "<<cnt<<endl;
	while(!q.empty())
	{
		cout<<q.front()<<endl;
		q.pop();
	}
	return 0;
}
相关推荐
xuxie9921 小时前
day 23 树
数据结构
晓131321 小时前
第二章 【C语言篇:入门】 C 语言基础入门
c语言·算法
jiang_changsheng21 小时前
环境管理工具全景图与深度对比
java·c语言·开发语言·c++·python·r语言
LYOBOYI1231 天前
qml的对象树机制
c++·qt
yong99901 天前
MATLAB面波频散曲线反演程序
开发语言·算法·matlab
LeoZY_1 天前
开源项目精选:Dear ImGui —— 轻量高效的 C++ 即时模式 GUI 框架
开发语言·c++·ui·开源·开源软件
JicasdC123asd1 天前
【工业检测】基于YOLO13-C3k2-EIEM的铸造缺陷检测与分类系统_1
人工智能·算法·分类
特立独行的猫a1 天前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
Not Dr.Wang4221 天前
自动控制系统稳定性研究及判据分析
算法
VT.馒头1 天前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript