ja / en
Overview

WeightedUnionFind

2024/07/29
2 min read

Purpose

A Union-Find with weights to manage distances between elements.

Time Complexity

O(α(n))O(\alpha(n)), where α\alpha is the inverse Ackermann function.

Usage

Declaration

WeightedUnionFind<distance_class> wuf(num_elements);

Query

Merge

uf.merge(a,b,w);

Merges the set containing a and the set containing b such that (weight of b) - (weight of a) = w, meaning b is heavier than a by w.

Determine if in the same set

wuf.isSame(a,b);

Determines whether a and b belong to the same set.

Set Size

wuf.size(a);

Returns the size of the set to which a belongs.

Difference in Weight

wuf.diff(a,b);

returns (weight of b) - (weight of a).

Implementation

template <class T>
class WeightedUnionFind {
public:
WeightedUnionFind(int n) : parents(n, -1), weights(n, 0) {}
int find(int i) {
if (parents[i] < 0)
return i;
weights[i] += weights[parents[i]];
return parents[i] = find(parents[i]);
}
void merge(int a, int b, T w) {
w += weight(a) - weight(b);
a = find(a), b = find(b);
if (a != b) {
if (-parents[a] < -parents[b]) {
swap(a, b);
w = -w;
}
parents[a] += parents[b];
parents[b] = a;
weights[b] = w;
}
}
T diff(int a, int b) {
return weight(b) - weight(a);
}
bool connected(int a, int b) {
return find(a) == find(b);
}
int size(int i) {
return -parents[find(i)];
}
private:
vector<int> parents;
vector<T> weights;
T weight(int i) {
find(i);
return weights[i];
}
};

Verify

//TODO