并查集
来源:互联网 发布:网络管理师考试 编辑:程序博客网 时间:2024/05/17 01:43
题目链接:点击打开链接
#include<cstdio>#define MAXN 1000 + 10int fa[MAXN];int find_set(int i){ if(fa[i] == i) return i; else return (find_set(fa[i]));}void union_set(int x,int y){ int root_x = find_set(x); int root_y = find_set(y); if(root_x != root_y) fa[root_x] = root_y;}int main(){ int n,m; int x,y; while(scanf("%d",&n) > 0) { if(!n) break; scanf("%d",&m); for(int i = 1; i <= n; i++) fa[i] = i; for(int i = 1; i <= m; i++) { scanf("%d%d",&x,&y); union_set(x,y); } int result = 0; for(int i = 1; i <= n; i++) if(fa[i] == i) result ++; printf("%d\n",result - 1); } return 0;}
使用rank和路径压缩优化后的代码如下:
#include<cstdio>#define MAXN 1000 + 10int fa[MAXN];struct Node {int father;int rank;}node[MAXN];int find_set(int i){if(node[i].father == i) return i;else{ node[i].father = find_set(node[i].father);return node[i].father;}}void union_set(int x,int y){int root_x = find_set(x);int root_y = find_set(y);if(root_x != root_y){if (node[root_x].rank > node[root_y].rank){node[root_y].father = root_x;node[root_x].rank ++;} else{node[root_x].father = root_y;node[root_y].rank++;}}}int main(){int n,m;int x,y;while(scanf("%d",&n) > 0){if(!n) break;scanf("%d",&m);for(int i = 1; i <= n; i++){node[i].father = i;node[i].rank = 0;}for(int i = 1; i <= m; i++){scanf("%d%d",&x,&y);union_set(x,y);}int result = 0;for(int i = 1; i <= n; i++) if(node[i].father == i) result ++;printf("%d\n",result - 1);}return 0;}
但是效果不是很好。。。。下图中109ms为优化后的运行时间。呵呵。。
0 0
- HDU3938 并查集 并查集
- 并查集(集并查)
- HDU1232 并查集<并>
- 并查集
- 数据结构-并查集
- 并查集
- 并查集!
- 并查集
- 并查集
- 并查集
- 并查集
- 并查集总结
- 并查集学习
- 并查集
- 并查集
- 并查集
- 所谓并查集
- 并查集
- 倾城之恋
- The selected wizard could not be started. Plug-in org.apache.hadoop.eclipse was unable to load class
- Redmine Agile plugin安装使用方法
- 删除字符串中的数字
- 说一下id3决策树
- 并查集
- 蓝桥有感,
- Android剪切板设置和读取字符串String 关键代码
- delphi窗体之间的相互传值
- 测试HTTP的方便法
- cocos2dx:数据存储-静态数据
- AStyle代码格式工具在source insight中的使用
- Codeforces Round #227 (Div. 2) / 387C George and Number (贪心)
- Struts2中的Could not find action or result