acl_cpp.dsu
dsu.dsu
# dsu
from acl_cpp.dsu import dsu
Given an undirected graph, processes the following queries in
adding edges
Deciding whether given two vertices are in the same connected component
Here,
Each connected component internally has a representative vertex.
When two connected components are merged by edge addition, one of the two representatives of these connected components becomes the representative of the new connected component.
Constructor
# dsu::dsu(int n)
def dsu(n: int = 0) -> dsu
Creates an undirected graph with
vertices and edges.
Constraints
Complexity
dsu.merge
# void dsu::merge(int a, int b)
def dsu.merge(a: int, b: int) -> None
Adds an edge
Returns the representative if
Constraints
Complexity
Amortized
dsu.same
# bool dsu::same(int a, int b)
def dsu.same(a: int, b: int) -> bool
Returns whether vertices
Constraints
Complexity
Amortized
dsu.leader
# int dsu::leader(int a)
def dsu.leader(a: int) -> int
Returns the representative of the connected component containing vertex
Constraints
Complexity
Amortized
dsu.size
# int dsu::size(int a)
def dsu.size(a: int) -> int
Returns the size of the connected component containing vertex
Constraints
Complexity
Amortized
dsu.groups
# vector<vector<int>> dsu::groups()
def dsu.groups() -> list[list[int]]
Divides the graph into connected components and returns that information.
The return value is a list of lists of vertex numbers, each representing a connected component. The order of vertices within each list and the order of the lists themselves are undefined.
Complexity
Examples
AC code of https://atcoder.jp/contests/practice2/tasks/practice2_a
from acl_cpp.dsu import dsu
N, Q = map(int, input().split())
d = dsu(N)
for _ in range(Q):
t, u, v = map(int, input().split())
if t == 0:
d.merge(u, v)
else:
print(int(d.same(u, v)))