並查集(Java)


並查集常常用來判斷在一個圖中是否存在回路(是否可以生成樹),以及用來判斷圖的聯通性問題。

這里介紹並查集的一種簡單且使用較多的一種實現方法——快速union,快速find,基於重量的並查集實現方法。

 

首先,需要兩個數組——parent[] 與weight[] ,parent用來存放該節點的父節點,weight用來存放該節點有多少的子節點,也就是該節點的“重量”。

其次,需要一個整數nums來記錄一共有多少個不相連的集合

並查集有三個基本的方法:init() , find() , union() 。init()用來對數組進行初始化,find()用來查找對應節點的根節點,union()用來連接節點。

1,init() 初始化

初始化時,每個節點的父節點都是他自身。每個節點對應的重量均為1,nums為集合中節點的數量,代碼如下:

void init()
{
    for(int i = 0 ; i < parent.length ; i ++)
    {
          parent[i] = i ;
          weight[i] = 1 ;        
    }
    nums = parent,length ;
}

2,find()查找對應節點的根節點

find() 在查找根節點時,一直比較節點與父節點是否相同,如果相同則說明該節點為根節點

int find(int p)
{
  while(parent[p] != p)
  {
    p = parent[p] ;
  }
  return p ;
}

3,union()連接兩節點對應的父節點

union()在連接兩個節點的父節點時,需要比較兩個節點的父節點的“重量”,將重量較大的節點看作為父節點將其合並,每合並一次,對應的nums的數量就會減一。

public static void union(int p,int q,int[] nodes,int[] weight)
{
    int n = find(p,nodes) ;
    int m = find(q,nodes) ;
    if(n == m ) return ;          //兩節點的父節點相同,說明已經連接
    if(weight[n] > weight[m])
    {
        nodes[m] = n ;
        weight[n] += weight[m] ;
        nums -- ;
    }
    else{
        nodes[n] = m ;
            weight[m] += weight[n] ;
        nums -- ;
    }
}    

注意:在創建parent與weight數組時,數組的大小常常為節點個數加一,因為元素的節點常常從1開始,所以,定義的數組從1開始計數更為方便。

下面看兩道題目:

1013 Battle Over Cities (25 分)

It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.

For example, if we have 3 cities and 2 highways connecting city1​​-city2​​ and city1​​-city3​​. Then if city1​​ is occupied by the enemy, we must have 1 highway repaired, that is the highway city2​​-city3​​.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 3 numbers N (<1000), M and K, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then M lines follow, each describes a highway by 2 integers, which are the numbers of the cities the highway connects. The cities are numbered from 1 to N. Finally there is a line containing K numbers, which represent the cities we concern.

Output Specification:

For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

Sample Input:

3 2 3
1 2
1 3
1 2 3

Sample Output:

1
0
0

這道題目是對並查集的一種典型應用,可以轉化為:每次占領一個城市,並查集連接時便略過該城市,最后查看有幾個互不相干的集合n,
便說明了至少還需要n-1條路,代碼如下:
import java.util.*;
public class BattleOverCities2 {
    static int[] weight ;
    static int[] parent;
    static int nums ;
    public static void main(String args[])
    {
        Scanner scanner = new Scanner(System.in);
        int cities = scanner.nextInt();
        int roads = scanner.nextInt();
        int checked = scanner.nextInt();
        int[][] road = new int[roads][2];
        for(int i = 0 ; i < roads ; i ++)
        {
            road[i][0] = scanner.nextInt();    //road用來記錄有多少條道路
            road[i][1] = scanner.nextInt();
        }
        int[] check = new int[checked] ;
        for(int i = 0 ; i < checked ; i ++)
        {
            check[i] = scanner.nextInt();      //check[]用來記錄被占領的城市
        }
        scanner.close();
        for(int i = 0 ; i < checked ; i ++)
        {
            init(cities);
            solve(road,check[i]);
            System.out.println(nums-2);
        }
    }
    public static void init(int cities)
    {
        parent = new int[cities+1] ;
        nums = cities ;
        weight = new int[cities+1] ;
        for(int i = 1 ; i < cities + 1 ; i ++)
        {
            parent[i] = i ;
            weight[i] = 1 ;
        }
    }
    public static int find(int citiy)
    {
        while(citiy != parent[citiy])
        {
            citiy = parent[parent[citiy]];
        }
        return citiy ;
    }
    public static void union(int[] road )
    {
        int citiy1 = find(road[0]) ;
        int citiy2 = find(road[1]) ;
        if(citiy1 == citiy2) return ;
        if(weight[citiy1] > weight[citiy2])
        {
            parent[citiy2] = citiy1 ;
            weight[citiy1] += weight[citiy2] ;
        }
        else{
            parent[citiy1] = citiy2 ;
            weight[citiy2] += weight[citiy1] ;
        }
        nums -- ;
    }
    public static void solve(int[][] road , int check)
    {
        for(int i = 0 ; i < road.length ; i ++)
        {
            if(road[i][0] == check || road[i][1] == check)  //當需要連接的城市中有一座被占領,則掠過這條路
                continue ;
            union(road[i]) ;
        }
    }
}

還有一道題目:

1021 Deepest Root (25 分)

A graph which is connected and acyclic can be considered a tree. The hight of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (104​​) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N1 lines follow, each describes an edge by given the two adjacent nodes' numbers.

Output Specification:

For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print Error: K components where K is the number of connected components in the graph.

Sample Input 1:

5
1 2
1 3
1 4
2 5

Sample Output 1:

3
4
5

Sample Input 2:

5
1 3
1 4
2 5
3 4

Sample Output 2:

Error: 2 components

這道題目需要求圖的生成樹的最大深度是多少,首先需要判斷圖是否都相連,這里用到了並查集,如果互不相連的集合數目大於1,則返回互不相連的
個數,如果為1,則使用dfs找到生成樹的最大深度,代碼如下:
import java.util.*;
public class DeepestRoot {
    static int nums ;
    public static void main(String args[])
    {
        Scanner scanner = new Scanner(System.in);
        nums = scanner.nextInt() ;
        int[] nodes = new int[nums + 1] ;
        int[] weight = new int[nums + 1] ;
        Map<Integer,List<Integer>> map = new HashMap<>() ;
        for(int i = 1 ; i < nums + 1 ; i ++)
        {
            nodes[i] = i ;
            weight[i] = 1 ;
        }
        int t = nums ;
        for(int i = 1 ; i < t ; i ++)
        {
            int p = scanner.nextInt() ;
            int q = scanner.nextInt() ;
            union(p,q,nodes,weight);
            if(!map.containsKey(p))
                map.put(p, new ArrayList<Integer>()) ;
            if(!map.containsKey(q))
                map.put(q, new ArrayList<Integer>()) ;
            map.get(p).add(q) ;
            map.get(q).add(p) ;
        }
        scanner.close();
        if(nums != 1) 
        {
            System.out.println("Error: "+nums+" components");
        }
        else{
            int max = 0 ;
            Map<Integer,List<Integer>> mp = new HashMap<>() ;
            for(int i = 1 ; i < t + 1 ; i ++)
            {
                
                if(map.get(i).size() == 1) 
                {
                    
                    int c = dfs(map,i,0,new int[t+1],0) ;
                    if(c > max)
                    {
                        mp.put(c, new ArrayList<>()) ;
                        mp.get(c).add(i);
                        max = c ;
                    }
                    else if(c == max)
                        mp.get(max).add(i) ;
                }
            }
            Collections.sort(mp.get(max));
            System.out.print(mp.get(max).get(0));
            for(int i = 1 ; i < mp.get(max).size() ; i ++)
            {
                System.out.println();
                System.out.print(mp.get(max).get(i));
            }
            
        }        
    }
    public static int dfs(Map<Integer,List<Integer>> map,int q,int count,int[] checked,int max)
    {
        checked[q] = 1 ;
        int p = 0 ;
        for(int i = 0 ; i < map.get(q).size() ; i ++)
        {
            int t = map.get(q).get(i);
            if(checked[t] == 1) continue ;
            int l = dfs(map,t,count+1,checked,max) ;
            if(max < l) max = l ;
            p ++ ;
        }
        if(p == 0) return count ;
        return max ;
    }
    public static int find(int n,int[] parent)
    {
        while(parent[n] != n)
        {
            n = parent[n] ;
        }
        return n ;
    }
    public static void union(int p,int q,int[] nodes,int[] weight)
    {
        int n = find(p,nodes) ;
        int m = find(q,nodes) ;
        if(n == m ) return ;
        if(weight[n] > weight[m])
        {
            nodes[m] = n ;
            weight[n] += weight[m] ;
            nums -- ;
        }
        else{
            nodes[n] = m ;
            weight[m] += weight[n] ;
            nums -- ;
        }
    }
}

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM