[HDU1232] 畅通工程 (并查集 or 连通分量)

Input

测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是城镇数目N ( < 1000 )和道路数目M;随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。 
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。 
 

 

Output

对每个测试用例,在1行里输出最少还需要建设的道路数目。 
 

 

Sample Input

4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
 
999 0
0
 

 

Sample Output

1
0
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 ); } } }

 

posted @ 2016-03-17 15:58  hudiwei-hdw  阅读(157)  评论(0编辑  收藏  举报