C++ 图论-并查集
来源:互联网 发布:网络建设与管理试题 编辑:程序博客网 时间:2024/06/10 04:43
并查集是快速实现大量数据的合并和查找,时间复杂度为O(log2n)
以下是两层并查集:(结点与自己的祖先直接相连)
1> 初始化 祖先赋为自己father[i=1~n] = i;
2> 并:若总根不同,将两个结点的总根合并:第一个总根做第二个总根的祖先
3> 查:查看father是否相同
#include <iostream>using namespace std;int n, m, q; //一共n个人,m对亲戚关系,q次查询int father[10001];int Find_f(int x) { //找总根 if(x == father[x]) return x; //说明x是总根 father[x] = Find_f(father[x]);return father[x];}int Unite(int a, int b) { //合并 int f1 = Find_f(a);int f2 = Find_f(b);if(f1 == f2) return 0; //f1 = f2 已经是亲戚关系 father[f2] = f1; return 1;}int main() {int x, y, c, d;cin >> n >> m >> q;for(int i=1; i<=n; i++) father[i] = i; //初始化 for(int i=1; i<=m; i++) {cin >> x >> y; Unite(x, y); //x、y成为亲戚 }for(int i=1; i<=n; i++) Find_f(i); //上面Unite只是合并总根,总根下的子结点还没更新 for(int i=1; i<=q; i++) {cin >> c >> d; //查询c、d是不是亲戚 if(father[c] == father[d]) cout << "Yes" << endl;else cout << "No" << endl;}return 0;}
阅读全文
0 0
- C语言 并查集
- [c] poj2524 并查集
- 并查集—C
- sdnu-并查集&图论-weeklyexam ——C
- 不相交集(并查集)(C++)
- 并查集(C语言)
- 并查集实现(C语言)
- 并查集C - More is better
- CodeForces 218C 并查集
- 【CodeForces】445C Civilization 并查集
- C语言 并查集基础
- C语言 并查集 压缩路径
- codeforces 650C (并查集)
- 并查集的实现c
- codeforce C. Learning Languages(并查集)
- codeforces 722C (并查集)
- codeforces 731C 并查集+贪心
- Codeforces 731C 并查集
- 二叉树的先序、中序、后序遍历(递归 and 非递归)
- 数据库读写分离的理解
- 3种预编译
- PAT 乙级 1022
- c语言三字母词(trigraph) && 整型提升
- C++ 图论-并查集
- 【CUGBACM15级BC第29场 B】hdu 5171 GTY's birthday gift
- 基本排序算法总结
- web.config 中SessionState的配置
- 几个问题
- day4_字符串反转问题
- 修改ternimal个性化设置
- Python:获取当前脚本路径的姿势对比
- shell杀死进程, adb server is out of date. killing