Problem solution · Python

ABC214 D — Sum of Maximum Weights

ABC214 D — Sum of Maximum Weights: 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
103 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 ABC214 D — Sum of Maximum Weights, 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

  • 103 lines of Python from the credited upstream file abc214_d.py.
  • The implementation visibly relies on sequence storage, ordered lookup.
  • 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 codeABC214 D — Sum of Maximum Weights · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  class UnionFind:    '''Represents a data structure that tracks a set of elements partitioned       into a number of disjoint (non-overlapping) subsets.    Landau notation: O(α(n)), where α(n) is the inverse Ackermann function.    See:    https://www.youtube.com/watch?v=zV3Ul2pA2Fw    https://en.wikipedia.org/wiki/Disjoint-set_data_structure    https://atcoder.jp/contests/abc120/submissions/4444942    '''     def __init__(self, number_count: int):        '''        Args:            number_count: The size of elements (greater than 2).        '''        self.parent_numbers = [-1 for _ in range(number_count)]     def find_root(self, number: int) -> int:        '''Follows the chain of parent pointers from number up the tree until           it reaches a root element, whose parent is itself.        Args:            number: The trees id (0-index).        Returns:            The index of a root element.        '''        if self.parent_numbers[number] < 0:            return number         self.parent_numbers[number] = self.find_root(self.parent_numbers[number])        return self.parent_numbers[number]     def get_group_size(self, number: int) -> int:        '''        Args:            number: The trees id (0-index).        Returns:            The size of group.        '''        return -self.parent_numbers[self.find_root(number)]     def is_same_group(self, number_x: int, number_y: int) -> bool:        '''Represents the roots of tree number_x and number_y are in the same           group.        Args:            number_x: The trees x (0-index).            number_y: The trees y (0-index).        '''        return self.find_root(number_x) == self.find_root(number_y)     def merge_if_needs(self, number_x: int, number_y: int) -> bool:        '''Uses find_root to determine the roots of the tree number_x and           number_y belong to. If the roots are distinct, the trees are combined           by attaching the roots of one to the root of the other.        Args:            number_x: The trees x (0-index).            number_y: The trees y (0-index).        '''        x = self.find_root(number_x)        y = self.find_root(number_y)         if x == y:            return False         if self.get_group_size(x) >= self.get_group_size(y):            self.parent_numbers[x] += self.parent_numbers[y]            self.parent_numbers[y] = x        else:            self.parent_numbers[y] += self.parent_numbers[x]            self.parent_numbers[x] = y        return True  def main():    import sys     input = sys.stdin.readline     n = int(input())    wuv = list()        for _ in range(n - 1):        ui, vi, wi = map(int, input().split())        ui -= 1        vi -= 1        wuv.append((wi, ui, vi))        uf = UnionFind(n)    ans = 0        for wi, ui, vi in sorted(wuv):        ans += wi * uf.get_group_size(ui) * uf.get_group_size(vi)        uf.merge_if_needs(ui, vi)        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 ↗