hdu1232 畅通工程 && poj2524 Ubiquitous Religions(并查集裸)
来源:互联网 发布:易迈互联比阿里云好吗 编辑:程序博客网 时间:2024/05/17 08:59
http://acm.hdu.edu.cn/showproblem.php?pid=1232
题意:给你n个点m条边,求再需要添加多少条边就可以变成一个连通图。
思路:并查集裸体,思路看并查集详解。
#include <stdio.h>#include <algorithm>#include <stdlib.h>#include <string.h>#include <iostream>using namespace std;typedef long long LL;const int N = 100010;const int INF = 0x3f3f3f3f;int pre[N], sum;int Find(int x){ int r = x; while(r != pre[r]) r = pre[r]; int i = x, j; while(pre[i] != r) { j = pre[i]; pre[i] = r; i = j; } return r;}void Union(int p1, int p2){ int x = Find(p1); int y = Find(p2); if(x != y) { pre[x] = y; sum--; }}int main(){ // freopen("in.txt", "r", stdin); int n, m, p1, p2; while(~scanf("%d", &n)) { if(n == 0) break; scanf("%d", &m); sum = n-1;//原本的边数 for(int i = 1; i <= n; i++) pre[i] = i; for(int i = 1; i <= m; i++) { scanf("%d%d", &p1, &p2); Union(p1, p2); } printf("%d\n", sum); } return 0;}
http://poj.org/problem?id=2524
题意:给你n个节点m个关系,每个关系代表两人在一个宗教,求宗教数量。
思路:刚开始连通分量,每加一条边减一个,最后即为所得。
#include <stdio.h>#include <algorithm>#include <stdlib.h>#include <string.h>#include <iostream>using namespace std;typedef long long LL;const int N = 100010;const int INF = 0x3f3f3f3f;int pre[N], sum;int Find(int x){ int r = x; while(r != pre[r]) r = pre[r]; int i = x, j; while(pre[i] != r) { j = pre[i]; pre[i] = r; i = j; } return r;}void Union(int p1, int p2){ int x = Find(p1); int y = Find(p2); if(x != y) { pre[x] = y; sum--; }}int main(){ // freopen("in.txt", "r", stdin); int n, m, p1, p2, Case = 1; while(~scanf("%d%d", &n, &m)) { if(n == 0 && m == 0) break; sum = n;//原本的连通分量数 for(int i = 1; i <= n; i++) pre[i] = i; for(int i = 1; i <= m; i++) { scanf("%d%d", &p1, &p2); Union(p1, p2); } printf("Case %d: %d\n", Case++, sum); } return 0;}
0 0
- hdu1232 畅通工程 && poj2524 Ubiquitous Religions(并查集裸)
- poj2524 Ubiquitous Religions(并查集求组数)
- POJ2524--Ubiquitous Religions(并查集)
- POJ2524——Ubiquitous Religions(并查集)
- POJ2524 - Ubiquitous Religions (并查集的基础应用)
- poj2524——Ubiquitous Religions(并查集)
- POJ2524 Ubiquitous Religions 并查集
- poj2524 Ubiquitous Religions 并查集入门
- POJ2524 Ubiquitous Religions 并查集
- 【并查集】:poj2524,Ubiquitous Religions
- 并查集-poj2524-Ubiquitous Religions
- POJ2524 Ubiquitous Religions(并查集)
- POJ2524 Ubiquitous Religions 并查集
- POJ2524 Ubiquitous Religions(简单并查集)
- POJ2524 Ubiquitous Religions (并查集)
- POJ2524 Ubiquitous Religions (并查集)
- POJ2524 Ubiquitous Religions (并查集)
- poj2524 Ubiquitous Religions
- zoj3261Connections in Galaxy War(并查集)
- java生成的公钥与私钥key转成openssl的rsa算法中的公钥与私钥key
- 20150129pixhawk飞控校准
- 【Leetcode】LRU Cache
- Pollard Rho 大数分解
- hdu1232 畅通工程 && poj2524 Ubiquitous Religions(并查集裸)
- 2000: 棋盘开关灯游戏 - 高斯消元|搜索
- SQL Server 插入百万级数据
- 认识HTML5的WebSocket
- pixhawk飞控解锁方法
- 函数式编程语言彻解彻悟
- 微信公众号入门笔记(一)启用服务器配置
- HDU5617 Jam's maze(dp)
- asterisk服务器搭建 入门教程