团体天梯练习 L2-024 部落
L2-024 部落
在一个社区里,每个人都有自己的小圈子,还可能同时属于很多不同的朋友圈。我们认为朋友的朋友都算在一个部落里,于是要请你统计一下,在一个给定社区中,到底有多少个互不相交的部落?并且检查任意两个人是否属于同一个部落。
输入格式:
输入在第一行给出一个正整数
其中
之后一行给出一个非负整数
输出格式:
首先在一行中输出这个社区的总人数、以及互不相交的部落的个数。随后对每一次查询,如果他们属于同一个部落,则在一行中输出
输入样例:
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
解题思路
很明显的并查集模板题。题中给出的是每个人关联的所有其他人的编号,不过编号是连续的,所以记录一下最大编号就行了(或者定义一个数组记录这个数字是否存在与集合中)。
/* 一切都是命运石之门的选择 El Psy Kongroo */
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<cmath>
#include<functional>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<double, double> pdd;
typedef pair<string, int> psi;
typedef __int128 int128;
#define PI acos(-1.0)
#define x first
#define y second
//int dx[4] = {1, -1, 0, 0};
//int dy[4] = {0, 0, 1, -1};
const int inf = 0x3f3f3f3f, mod = 1e9 + 7;
const int N = 1e4 + 10;
int n, m, k, fa[N], s[N];
//m记录最大编号
void init(){
for(int i = 1; i < N; i ++ ) fa[i] = i, s[i] = 1;
}
int find(int x){
return fa[x] == x ? x : (fa[x] = find(fa[x]));
}
void Union(int x, int y){
int fx = find(x), fy = find(y);
if(fx == fy) return;
fa[fx] = fy;
s[fy] += s[fx];
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n;
init();
while(n -- ){
cin >> k;
int a; cin >> a;
m = max(m, a);
k -- ;
while(k -- ){
int b; cin >> b;
Union(a, b);
m = max(m, b);
}
}
int cnt = 0, sum = 0;
for(int i = 1; i <= m; i ++ )
if(fa[i] == i) cnt ++ , sum += s[i];
cout << sum << ' ' << cnt << endl;
int q; cin >> q;
while(q -- ){
int a, b; cin >> a >> b;
int fx = find(a), fy = find(b);
if(fx == fy) cout << "Y" << endl;
else cout << "N" << endl;
}
return 0;
}
一切都是命运石之门的选择,本文章来源于博客园,作者:MarisaMagic,出处:https://www.cnblogs.com/MarisaMagic/p/17331741.html,未经允许严禁转载
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具