[HDU1232] 畅通工程 (并查集 or 连通分量)
2016-03-17 15:58
387 查看
Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最少还需要建设的道路数目。Sample Input
4 21 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0
Sample Output
10
2
998
这题是一个很经典的并查集题目了,也是最基础的了,当做学习~
import java.util.Scanner; public class Main { public static int[] parent; public static boolean[] root; public static int find(int x){ int top = x; //找出顶层父节点 while(parent[top] != top){ top = parent[top]; } //减少深度,路径压缩 int c2 = x; int temp; while(c2!=top){ temp = parent[c2]; parent[c2] = top; c2 = temp; } return top; } public static void union(int x,int y){ int fx = find(x); int fy = find(y); //如果不是同一顶层父节点则随机一个联合 if(fx != fy){ parent[fy] = fx; } } public static void main( String[] args ) { Scanner sc = new Scanner(System.in); int n,m; while(sc.hasNext()){ int answer=0; n = sc.nextInt(); if(n==0) return ; m = sc.nextInt(); parent = new int[n+1]; root = new boolean[n+1]; for(int i=1;i<=n;i++){ parent[i] = i; } for(int i=0;i<m;i++){ union( sc.nextInt(), sc.nextInt() ); } for(int i=1;i<=n;i++){ root[find( i )] = true; } for(int i=1;i<=n;i++){ if(root[i]){ answer++; } } System.out.println( answer-1 ); } } }
相关文章推荐
- OC中block作方法参数时的用法
- Lucene的中文分词器IKAnalyzer
- POJ 3984 迷宫问题(BFS)
- 3357: [Usaco2004]等差数列 DP+map
- 课堂笔记1
- 三盘惠普双循环的磁盘阵列恢复
- caffe代码阅读5:Layer的实现细节-2016.3.17
- react-native Navigator 填坑
- python 刷题:变态跳台阶
- 使用Handler来对线程之间传值
- rpm解压命令,rpm不仅仅可以安装,还可以解压
- KMP UVALive326 Period
- 如何修复在Ubuntu14.04状态栏不显示时间的问题
- 3月15日
- [国嵌攻略][153][I2C裸机驱动设计]
- Java之Filter过滤器
- centos7 yum 更新出现 [Errno 14] HTTP Error 404 - Not Found 的解决方法
- 简单好用的tab切换页面
- 操作系统 实验一 命令解释程序的编写
- OpenStack 系列之Manila install and using the Virtualenv