Problem solution · Python

ABC424 C — New Skill Acquired

ABC424 C — New Skill Acquired: a Python solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Disjoint set union
Source
KATO-Hiro AtCoder Solutions
Length
47 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For ABC424 C — New Skill Acquired, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. Answer connectivity or component queries from the compressed representatives.

Code notes

  • 47 lines of Python from the credited upstream file abc424_c.py.
  • The implementation visibly relies on hash lookup, ordered lookup, work queue.
  • No explicit loop blocks detected.

Complexity

Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from KATO-Hiro AtCoder Solutions by KATO-Hiro and is used under the CC0-1.0 licence.

Full codeABC424 C — New Skill Acquired · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    import sys     from collections import deque, defaultdict    from atcoder.dsu import DSU     input = sys.stdin.readline     n = int(input())    d = defaultdict(set)     for i in range(n):        ai, bi = map(int, input().split())         d[ai].add(i + 1)        d[bi].add(i + 1)     q = deque([0])    used = set()    dsu = DSU(n + 1)     while q:        cur = q.popleft()         if cur in used:            continue         used.add(cur)         for to in d[cur]:            dsu.merge(cur, to)             if to in used:                continue             q.append(to)     ans = dsu.size(dsu.leader(0)) - 1    print(ans)  if __name__ == "__main__":    main() 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗