Как я могу реализовать алгоритм Union-Find? - PullRequest
0 голосов
/ 21 мая 2019

Я пытаюсь реализовать алгоритм Union-Find, но все реализации, которые я искал, используют целые числа. Мне нужно реализовать алгоритм, чтобы я мог вызывать методы union () и connected () следующим образом: union (Vertex v, Vertex, w) - connected (Vertex v, Vertex w)

Я пытался адаптировать свой алгоритм для работы с вершинами, но я не знаю, как заменить атрибуты родителя и ранга, чтобы он работал. Пожалуйста, помогите: (

открытый класс UF {

private int[] parent;  // parent[i] = parent of i
private byte[] rank;   // rank[i] = rank of subtree rooted at i (never more than 31)
private int count;     // number of components

/**
 * Initializes an empty union–find data structure with {@code n} sites
 * {@code 0} through {@code n-1}. Each site is initially in its own 
 * component.
 *
 * @param  n the number of sites
 * @throws IllegalArgumentException if {@code n < 0}
 */
public UF(int n) {
    if (n < 0) throw new IllegalArgumentException();
    count = n;
    parent = new int[n];
    rank = new byte[n];
    for (int i = 0; i < n; i++) {
        parent[i] = i;
        rank[i] = 0;
    }
}

/**
 * Returns the component identifier for the component containing site {@code p}.
 *
 * @param  p the integer representing one site
 * @return the component identifier for the component containing site {@code p}
 * @throws IllegalArgumentException unless {@code 0 <= p < n}
 */
public int find(int p) {
    validate(p);
    while (p != parent[p]) {
        parent[p] = parent[parent[p]];    // path compression by halving
        p = parent[p];
    }
    return p;
}

/**
 * Returns the number of components.
 *
 * @return the number of components (between {@code 1} and {@code n})
 */
public int count() {
    return count;
}

/**
 * Returns true if the the two sites are in the same component.
 *
 * @param  p the integer representing one site
 * @param  q the integer representing the other site
 * @return {@code true} if the two sites {@code p} and {@code q} are in the same component;
 *         {@code false} otherwise
 * @throws IllegalArgumentException unless
 *         both {@code 0 <= p < n} and {@code 0 <= q < n}
 */
public boolean connected(int p, int q) {
    return find(p) == find(q);
}

/**
 * Merges the component containing site {@code p} with the 
 * the component containing site {@code q}.
 *
 * @param  p the integer representing one site
 * @param  q the integer representing the other site
 * @throws IllegalArgumentException unless
 *         both {@code 0 <= p < n} and {@code 0 <= q < n}
 */
public void union(int p, int q) {
    int rootP = find(p);
    int rootQ = find(q);
    if (rootP == rootQ) return;

    // make root of smaller rank point to root of larger rank
    if      (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;
    else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;
    else {
        parent[rootQ] = rootP;
        rank[rootP]++;
    }
    count--;
}

// validate that p is a valid index
private void validate(int p) {
    int n = parent.length;
    if (p < 0 || p >= n) {
        throw new IllegalArgumentException("index " + p + " is not between 0 and " + (n-1));  
    }
}

}

1 Ответ

0 голосов
/ 21 мая 2019

В стандартном алгоритме каждой вершине присваивается идентификатор int, который представляет ее место в массиве. Таким образом, это означает, что parent[0] содержит идентификатор родителя вершины 0 и т. Д.

Действительно, вы можете считать массивы просто очень эффективной картой от int до чего-то еще. Если вы замените int более сложным типом, вам нужно начать использовать Map вместо массива.

Итак, если вы хотите использовать класс с именем Vertex для представления вершин, вам нужно объявить родителей и ранги по-другому:

Map<Vertex,Vertex> parent = new HashMap<>();
Map<Vertex,Rank> rank = new HashMap<>();

Вы можете заменить Rank на Byte, если хотите придерживаться текущей схемы - хотя, вероятно, лучше использовать инкапсуляцию для использования класса.

Затем вы получите код, который выглядит примерно так:

while (!vertex.equals(parent.get(vertex))) {
    parent.put(vertex, parent.get(parent.get(vertex)));
    vertex = parent.get(vertex);
}
return vertex;

Следует помнить, что если вы собираетесь использовать Vertex в качестве ключа карты (как я рекомендовал), то вы должны реализовать equals и hashCode методы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...