HDU1213:How Many Tables(並查集入門)

-----------刷點水題練習java-------------java

題意:給定N點,M邊的無向圖,問有多少個連通塊。數組

思路:能夠搜索;  能夠並查集。這裏用並查集練習java的數組使用,ans=N,合併一個連通塊ans--; 以及函數的調用函數

         經驗1:C++聲明數組是int fa[1024];而java則是int[] fa=new int[1024];spa

        經驗2:不加static是非靜態函數,訪問須要new出該類的對象來調用,加上static是靜態函數 可直接訪問或者經過類名訪問。code

import java.util.Scanner;

/*
@author nimphy
@create 2019-11-04-16:14
about:
*/
public class Main {
    static int[] fa = new int[1010];

    public static void main(String[] args) {
        Scanner scan;
        int N, M, ans, x, y, T;
        scan = new Scanner(System.in);
        T = scan.nextInt();
        while (T-- > 0) {
            N = scan.nextInt();
            M = scan.nextInt();
            ans = N;
            for (int i = 1; i <= N; i++) fa[i] = i;
            for (int i = 1; i <= M; i++) {
                x = scan.nextInt();
                y = scan.nextInt();
                x = find(x);
                y = find(y);
                if (x != y) {
                    fa[x] = y;
                    ans--;
                }
            }
            System.out.println(ans);
        }
    }

    static int find(int x) {
        if (x == fa[x]) return x;
        return fa[x] = find(fa[x]);
    }
}
相關文章
相關標籤/搜索