【Union Find】JAVA implementation

本文介绍了一种并查集的数据结构及其优化方法,通过引入大小平衡策略,有效地减少了查找路径长度,提高了并查集的效率。文章展示了如何利用Java实现这一优化过程,并提供了一个完整的示例程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

class UF
{
	private int[] id;
	private int count;
	
	public UF(int N)
	{
		count = N;
		id = new int[N];
		for (int i = 0; i < N; i++) {
			id[i] = i;
		}
	}
	public int count(){
		return count;
	}
	public int find(int p){
		while (p != id[p]) {
			p = id[p];
		}
		return p;
	}
	public boolean connected(int p, int q){
		return find(p) == find(q);
	}
	public void union(int p, int q){
		int proot = find(p);
		int qroot = find(q);
		
		if (proot == qroot) {
			return;
		}
		id[proot] = qroot;
		count--;
	}
	public String toString()
	{
		return Arrays.toString(id);
	}
}

public class Main {
    
    public static void main(String[] args) 
    {
        Scanner jin = new Scanner(System.in);
        int N = jin.nextInt();
        UF uf = new UF(N);
        while (jin.hasNext()) {
			int p = jin.nextInt();
			int q = jin.nextInt();
			if (uf.connected(p, q)) {
				continue;
			}
			uf.union(p, q);
		}
        System.out.println(uf.count());
        
        System.out.println(uf);
        
    } 
}

对两棵树的合并操作做优化,引入变量size表示这棵树的结点个数,合并时,总是使size小的链接到size大的树。这样合并得到的森林,如果有N个结点,那么树的深度

不会超过lgN。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

class UF
{
	private int[] id;
	private int[] size;
	private int count;
	
	public UF(int N)
	{
		count = N;
		id = new int[N];
		size = new int[N];
		for (int i = 0; i < N; i++) {
			id[i] = i; size[i] = 1;
		}
	}
	public int count(){
		return count;
	}
	public int find(int p){
		while (p != id[p]) {
			p = id[p];
		}
		return p;
	}
	public boolean connected(int p, int q){
		return find(p) == find(q);
	}
	public void union(int p, int q){
		int proot = find(p);
		int qroot = find(q);
		
		if (proot == qroot) {
			return;
		}
		if (size[proot] < size[qroot]) { id[proot] = qroot; size[qroot] += size[proot];}
		else {id[qroot] = proot; size[proot] += size[qroot];}
		count--;
	}
	public String toString()
	{
		return Arrays.toString(id);
	}
}

public class Main {
    
    public static void main(String[] args) 
    {
        Long n;
        //System.out.println(Long.MAX_VALUE);
        Scanner jin = new Scanner(System.in);
        int N = jin.nextInt();
        UF uf = new UF(N);
        while (jin.hasNext()) {
			int p = jin.nextInt();
			int q = jin.nextInt();
			if (uf.connected(p, q)) {
				continue;
			}
			uf.union(p, q);
		}
        System.out.println(uf.count());
        
        System.out.println(uf);
        
    } 
}


### LeetCode Top 100 Problems with Java Solutions and Explanations LeetCode serves as an essential resource for developers aiming to enhance skills through solving algorithmic challenges[^1]. For individuals seeking guidance specifically on popular questions using Java, several resources provide comprehensive coverage. A notable approach involves focusing on dynamic programming, arrays, strings, trees, graphs, backtracking, depth-first search (DFS), breadth-first search (BFS), heaps, binary indexed tree, segment tree, bit manipulation, union find, two pointers, sliding window, greedy algorithms, divide & conquer among others. Each category has representative problems that frequently appear within the top 100 list: #### Example Problem: Maximum Subarray One classic example from this collection is **Maximum Subarray**, which can be efficiently solved via Kadane's Algorithm. Herein lies its implementation along with explanation: ```java class Solution { public int maxSubArray(int[] nums) { int n = nums.length; int max = Integer.MIN_VALUE, sum = 0; for (int i = 0; i < n; i++) { sum += nums[i]; max = Math.max(sum, max); if (sum < 0) sum = 0; } return max; } } ``` The logic behind this solution revolves around maintaining a running total (`sum`) while iterating over elements. Whenever `sum` drops below zero, resetting it ensures only positive contributions towards potential maximum subarrays are considered[^5]. To explore more such problems systematically, one might refer to curated lists available online or repositories dedicated to documenting solutions like those found at specific project addresses[^2]. These often include detailed analyses alongside code snippets tailored primarily toward enhancing comprehension beyond mere functionality.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值