并查集的理解与java实现

参考博客:https://www.cnblogs.com/SeaSky0606/p/4752941.html

package practice;
import java.util.Scanner;

public class unionfind {
	int count;
	int[] id;
	public unionfind(int N) {
		count = N;
		id = new int[N];
		for(int i = 0; i < N; i++) {
			id[i] = i;
		}
	}
	
	public int get_count() {
		return this.count;
	}
	
	public int find(int x) {
		return id[x];
	}
	
	public void union(int p, int q) {
		int pid = find(p);
		int qid = find(q);
		for(int i = 0; i < id.length; i++) {
			if(find(i) == pid) {
				id[i] = qid;
			}
		}
		count--;
	}
	
	public boolean connected(int p, int q) {
		return find(p) == find(q);
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int N = input.nextInt();
		unionfind buf = new unionfind(N);
		while(input.hasNext()) {
			String pair = input.next();
			if(pair.equals("exit")) break;
			int p = Integer.parseInt(pair.split("-")[0]);
			int q = Integer.parseInt(pair.split("-")[1]);
			if(buf.connected(p, q)) continue;
			buf.union(p, q);
		}
		System.out.println(buf.get_count());
		input.close();
	}

}

优化复杂度的版本:

import java.util.*;

public class unionfind_v1 {
	int count;
	int[] id;
	public unionfind_v1(int N){
		count = N;
		id = new int[N];
		for(int i = 0; i < N; i++) {
			id[i] = i;
		}
	}
	
	public int get_count() {
		return this.count;
	}
	
	public int find(int x) {
		while(x != id[x]) x = id[x];
		return x;
	}
	
	public void union(int p, int q) {
		int pid = id[p];
		int qid = id[q];
		if(pid == qid) return;
		id[qid] = pid;
		count--;
	}
	
	public boolean connected(int p, int q) {
		return find(p) == find(q);
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int N = input.nextInt();
		unionfind_v1 buf = new unionfind_v1(N);
		while(input.hasNext()) {
			String pair = input.next();
			if(pair.equals("exit")) break;
			int p = Integer.parseInt(pair.split("-")[0]);
			int q = Integer.parseInt(pair.split("-")[1]);
			if(buf.connected(p, q)) continue;
			buf.union(p, q);
		}
		System.out.println(buf.get_count());
		input.close();
	}
}

 

你可能感兴趣的:(数据结构与算法)