并查集
来源:互联网 发布:交易平台软件 编辑:程序博客网 时间:2024/05/29 13:02
#include <bits/stdc++.h>
int fa[2000];
// 还记得之前阅读课里讲的并查集算法
// father函数返回的是节点x的祖先节点
int father(int x) {
if (fa[x] != x) fa[x] = father(fa[x]);
return fa[x];
}
// 合并两个节点所在集合,同时判断两个点之前是否在一个集合里
// 函数返回true则之前两个点不在一个集合中
bool join(int x, int y) {
int fx = father(x), fy = father(y);
if (fx != fy) {
fa[fx] = fy;
return true;
} else {
return false;
}
}
// 初始化一个n个点的并查集
void init(int n) {
for (int i = 1; i <= n; ++i) fa[i] = i;
}
int main(){
//第一行两个整数,表示句子数量n(1<=n<=1000),表示人数m(1<=m<=1000)
int n, m, result = 0;
scanf("%d%d", &n, &m);
init(n);
int
while(n--){
int x, y;
scanf("%d%d", &x, &y);
if(join(x, y)){
result++;
}
}
printf("%d\n", result);
return 0;
}
int fa[2000];
// 还记得之前阅读课里讲的并查集算法
// father函数返回的是节点x的祖先节点
int father(int x) {
if (fa[x] != x) fa[x] = father(fa[x]);
return fa[x];
}
// 合并两个节点所在集合,同时判断两个点之前是否在一个集合里
// 函数返回true则之前两个点不在一个集合中
bool join(int x, int y) {
int fx = father(x), fy = father(y);
if (fx != fy) {
fa[fx] = fy;
return true;
} else {
return false;
}
}
// 初始化一个n个点的并查集
void init(int n) {
for (int i = 1; i <= n; ++i) fa[i] = i;
}
int main(){
//第一行两个整数,表示句子数量n(1<=n<=1000),表示人数m(1<=m<=1000)
int n, m, result = 0;
scanf("%d%d", &n, &m);
init(n);
int
while(n--){
int x, y;
scanf("%d%d", &x, &y);
if(join(x, y)){
result++;
}
}
printf("%d\n", result);
return 0;
}
0 0
- HDU3938 并查集 并查集
- 并查集(集并查)
- HDU1232 并查集<并>
- 并查集
- 数据结构-并查集
- 并查集
- 并查集!
- 并查集
- 并查集
- 并查集
- 并查集
- 并查集总结
- 并查集学习
- 并查集
- 并查集
- 并查集
- 所谓并查集
- 并查集
- 资深编程专家:C++ STL编程轻松入门方法分享
- SHELL syntax error:unexpected end of file 提示错误
- Android MediaPlayer
- ScrollView和ViewPager滑动冲突的解决和整理
- NYOJ104 最大和
- 并查集
- 【Unity3D游戏开发】基于NGUI的表情图文混排解决方案 (二二)
- 十道海量数据处理面试题与十个方法大总结(转)
- 语言检测工具language-detection 的简单使用
- matlab——小波包变换
- zoj--3878--Convert QWERTY to Dvorak(纯暴力)
- 206. Reverse Linked List [easy] (Python)
- 并发框架Executor相关类解析
- Mysql 乐观锁