Official

G - 地域の特産品 / Local Specialty Products Editorial by admin Editorial for printing

Claude Opus 5 (High)

Overview

This problem asks us to find the maximum vertex weight \(A_i\) within each connected component of an undirected graph and output this maximum for every vertex. It can be solved by maintaining the maximum value for each connected component using a Union-Find (Disjoint Set Union) data structure or BFS/DFS.

Analysis

Key Observation

The relation “it is possible to travel from town \(u\) to town \(v\)” is precisely connectivity in an undirected graph. This relation satisfies:

  • Reflexivity: It is possible to travel from \(u\) to \(u\) (using \(0\) roads).
  • Symmetry: Since roads are bidirectional, if \(u \to v\), then \(v \to u\).
  • Transitivity: If \(u \to v\) and \(v \to w\), then \(u \to w\).

Because it satisfies these properties, it is an equivalence relation, partitioning the set of towns into groups known as “connected components”.

Therefore, the answer is the same for all towns belonging to the same connected component, and this value is the maximum of \(A_i\) among the towns in that component.

For example, when \(N = 5\), \(A = (3, 7, 2, 9, 5)\), and the roads are \((1,2), (4,5)\), the connected components are \(\{1,2\}, \{3\}, \{4,5\}\), and the answers in order are \(7, 7, 2, 9, 9\).

Issues with the Naive Approach

A naive method that performs a BFS or DFS for each town \(i\) to explore all reachable towns and find the maximum will yield the correct answer. However, since each search takes \(O(N+M)\) time, the overall time complexity would be \(O(N(N+M))\). With \(N, M \le 2 \times 10^5\), this will far exceed the time limit (on the order of \(10^{10}\) operations).

Solution

Exploring towns in the same component multiple times is redundant. Therefore, we should:

  • Determine which component each town belongs to only once.
  • Compute the maximum value for each component only once.

A representative tool to achieve this is Union-Find (this is also equally possible using BFS/DFS by visiting every vertex exactly once).

Algorithm

We use a Union-Find (Disjoint Set Union) data structure. The key idea is to store the maximum value of \(A\) for each group at its representative element (the root).

  1. Initialization: Treat each town \(i\) as an individual group and set best[i] = A[i].
  2. For each road \((U_j, V_j)\), find the root \(r_u\) of \(U_j\) and the root \(r_v\) of \(V_j\).
    • If \(r_u = r_v\) (already in the same group), do nothing. This naturally ignores multi-edges and self-loops.
    • If they are different, merge them by making one root the child of the other, and update best of the new root to \(\max(best[r_u], best[r_v])\).
  3. Finally, find the root \(r\) for each town \(i\) and output best[r].

As long as best is correctly maintained at the root, it does not matter if the values stored at child nodes become outdated (since we always refer to the value at the root).

Correctness: By induction, we can show that each group in the Union-Find always corresponds to the set of towns connected by the roads processed so far, and best holds the maximum value within that group. After processing all roads, each group corresponds exactly to a connected component.

To maintain the desired time complexity, we implement either (or both) of the following optimization techniques:

  • Path compression: Reattach the parent of each vertex visited during the search directly to the root.
  • Union by size/rank: Make the root of the tree with larger size (or rank) the new root.

In this implementation, path compression is used, and merging is done by making the node with the larger best value the root (which simplifies updating best). With path compression alone, the amortized time complexity per operation is roughly \(O(\log N)\), which is fast enough in practice.

Complexity

  • Time Complexity: \(O((N + M)\,\alpha(N))\) (\(\alpha\) is the inverse Ackermann function, which is practically constant. Even with path compression alone, it is \(O((N+M)\log N)\), which is plenty fast).
  • Space Complexity: \(O(N + M)\)

Implementation Details

  • Fast I/O for input: Since \(N, M\) are on the order of \(2\times 10^5\), repeatedly calling input() in Python will be slow. It is safe to read everything at once using sys.stdin.buffer.read().split() and convert to integers using an index pointer.
  • Bulk output: Printing \(N\) lines by calling print \(N\) times is also slow, so it is better to accumulate the results in a list and output them all at once using '\n'.join(...).
  • Avoiding recursion: Writing find recursively risks hitting the recursion limit when \(N = 2\times 10^5\). Writing it iteratively with two loops—one loop to find the root and another to compress the path (point parents to the root)—as shown below is safe.
# Find the root
x = u
while parent[x] != x:
    x = parent[x]
root = x
# Path compression
x = u
while parent[x] != x:
    nxt = parent[x]
    parent[x] = root
    x = nxt
  • Multi-edges and self-loops: In Union-Find, these are handled automatically because we do nothing when the roots are the same, so there is no need to deduplicate edges beforehand.

  • 1-based indexing: Since town numbers are 1-based, allocating parent and best with length \(N+1\) and mapping best[i] = A[i-1] helps prevent off-by-one errors.

  • When \(M = 0\) (there are no roads at all), each town forms its own component, and the answer is simply \(A_i\) itself. The code naturally handles this case without special treatment.

    Source Code

import sys

def main():
    data = sys.stdin.buffer.read().split()
    n = int(data[0]); m = int(data[1])
    a = data[2:2+n]
    A = [int(x) for x in a]
    parent = list(range(n + 1))
    best = [0] * (n + 1)
    for i in range(1, n + 1):
        best[i] = A[i-1]

    idx = 2 + n
    for _ in range(m):
        u = int(data[idx]); v = int(data[idx+1]); idx += 2
        # find root u
        x = u
        while parent[x] != x:
            x = parent[x]
        ru = x
        x = u
        while parent[x] != x:
            nxt = parent[x]
            parent[x] = ru
            x = nxt
        x = v
        while parent[x] != x:
            x = parent[x]
        rv = x
        x = v
        while parent[x] != x:
            nxt = parent[x]
            parent[x] = rv
            x = nxt
        if ru != rv:
            if best[ru] < best[rv]:
                ru, rv = rv, ru
            parent[rv] = ru
            if best[ru] < best[rv]:
                best[ru] = best[rv]

    out = []
    for i in range(1, n + 1):
        x = i
        while parent[x] != x:
            x = parent[x]
        r = x
        x = i
        while parent[x] != x:
            nxt = parent[x]
            parent[x] = r
            x = nxt
        out.append(best[r])
    sys.stdout.write('\n'.join(map(str, out)) + '\n')

main()

This editorial was generated by claude5opus-high.

posted:
last update: