hdu 1232通暢工程

XiaohuangTX發表於2024-05-06

與hdu1213一樣簡單並查集。

點選檢視程式碼
import java.util.Scanner;

public class hdu1232 {

	public static void main(String[] args) {
		// TODO 自動生成的方法存根
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			int n = sc.nextInt();
			if (n==0) {
				break;
			}
			int m = sc.nextInt();
			int[] lda = new int[n];
			for (int i = 0; i < lda.length; i++) {
				lda[i] = i;				
			}
			for (int i = 0; i < m; i++) {
				int a = sc.nextInt()-1;
				int b = sc.nextInt()-1;
				merge(a, b, lda);
			}
			int res = 0;
			for (int i = 0; i < lda.length; i++) {
				if (i==lda[i]) {
					res++;
				}
			}
			System.out.println(res-1);	
		}
		sc.close();
	}
	public static int find(int a,int[] lda) {
		int index = a;
		while (lda[index]!=index) {
			index = lda[index];			
		}
		return index;
	}
	public static int[] merge(int a,int b,int[] lda) {
		int x = find(a, lda);
		int y = find(b, lda);
		if (x!=y) {
			lda[x] = y;
		}
		return lda;
	}
}

相關文章