Tananyag‎ > ‎Algoritmusok‎ > ‎

Unió-holvan

public class UnioHolvan {

    private int n;
    private int[] apa;

    public UnioHolvan(int n) {
        apa = new int[n];
        for (int i = 0; i < n; ++i) {
            apa[i] = i;
        }
    }
    
    public int holvan(int a) {
        if(apa[a] == a)
            return a;
        return apa[a] = holvan(apa[a]);
    }
    
    public void unio(int a, int b) {
        apa[holvan(a)] = holvan(b);
    }
}

Hasonló