This documentation is automatically generated by online-judge-tools/verification-helper
#include "Library/DataStructure/WeightedUnionFind.hpp"$N$ 頂点からなる無向グラフに対して、辺の重みを管理しながら連結成分を管理するデータ構造です。
各要素間の重み(ポテンシャル)をアーベル群 $A$ で管理します。
WeightedUnionFind(int n)
制約
計算量
int Find(const int k)
制約
計算量
Abel Weight(const int k)
制約
計算量
Abel Diff(const int x, const int y)
Weight(y) - Weight(x) を返します。制約
計算量
bool Same(const int x, const int y)
制約
計算量
bool Unite(int x, int y, Abel w)
Weight(y) - Weight(x) = w となるように連結されます。false を返し、新たに連結された場合は true を返します。制約
計算量
#include "../Common.hpp"
template<typename Abel = int32_t>
class WeightedUnionFind{
public:
WeightedUnionFind(int n) : data_(n, -1), weight_(n, Abel{}){}
int Find(const int k){
if(data_[k] < 0) return k;
int r = Find(data_[k]);
weight_[k] += weight_[data_[k]];
return data_[k] = r;
}
Abel Weight(const int k){
Find(k);
return weight_[k];
}
Abel Diff(const int x, const int y){
return Weight(y) - Weight(x);
}
bool Same(const int x, const int y){
return Find(x) == Find(y);
}
bool Unite(int x, int y, Abel w){
w += Weight(x) - Weight(y);
x = Find(x), y = Find(y);
if(x == y) return false;
if(data_[x] > data_[y]) swap(x, y), w = -w;
data_[x] += data_[y];
data_[y] = x;
weight_[y] = w;
return true;
}
private:
vector<int> data_;
vector<Abel> weight_;
};#line 2 "Library/Common.hpp"
/**
* @file Common.hpp
*/
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cstdint>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;
using ll = int64_t;
using ull = uint64_t;
constexpr const ll INF = (1LL << 62) - (3LL << 30) - 1;
#line 2 "Library/DataStructure/WeightedUnionFind.hpp"
template<typename Abel = int32_t>
class WeightedUnionFind{
public:
WeightedUnionFind(int n) : data_(n, -1), weight_(n, Abel{}){}
int Find(const int k){
if(data_[k] < 0) return k;
int r = Find(data_[k]);
weight_[k] += weight_[data_[k]];
return data_[k] = r;
}
Abel Weight(const int k){
Find(k);
return weight_[k];
}
Abel Diff(const int x, const int y){
return Weight(y) - Weight(x);
}
bool Same(const int x, const int y){
return Find(x) == Find(y);
}
bool Unite(int x, int y, Abel w){
w += Weight(x) - Weight(y);
x = Find(x), y = Find(y);
if(x == y) return false;
if(data_[x] > data_[y]) swap(x, y), w = -w;
data_[x] += data_[y];
data_[y] = x;
weight_[y] = w;
return true;
}
private:
vector<int> data_;
vector<Abel> weight_;
};