G - 地域の特産品 / Local Specialty Products Editorial by admin Editorial for printing
Gemini 3.8 Flash (High)Overview
In an undirected graph, this problem asks us to find, for every vertex, the maximum weight \(A_i\) among all vertices in the connected component to which that vertex belongs.
Analysis
Problem Structure: The relation “city \(v\) is reachable from city \(u\) via roads” is an equivalence relation. Therefore, the set of cities is partitioned into several mutually reachable groups (connected components). Since all cities belonging to the same group can reach one another, the answer for all cities in a given group is identical: “the maximum value of the local specialty in that group.”
Naive Approach and Its Issues: One possible idea is to run a Depth-First Search (DFS) or Breadth-First Search (BFS) from each city \(i\) to explore all reachable cities and find the maximum value among them. However, this method takes \(O(N + M)\) time in the worst case for a single city, resulting in an overall time complexity of \(O(N(N + M))\), which will exceed the time limit (TLE).
Efficient Solution: We can utilize a Union-Find (Disjoint Set Union, DSU) data structure, which can efficiently manage connected components. Initially, each city forms an independent group, and the maximum value of each group is the value of that city’s own specialty. As we unite (merge) cities connected by roads, we can update the maximum value of the merged group at the same time, allowing us to compute the answers efficiently.
Algorithm
We can process the problem using Union-Find as follows:
- Initialization:
- For each city \(i\) (\(1 \le i \le N\)), create a group with itself as the parent.
- Initialize the maximum specialty value stored at the representative (root) of each group as
max_val[i] = A_i.
- Processing Road Information (Merging Groups):
- For each road \((U_j, V_j)\), find the roots of the groups containing \(U_j\) and \(V_j\).
- If the roots are different, merge the two groups.
- For the new root, record the larger of the maximum values of the two groups: \(\text{max\_val}[\text{new\_root}] = \max(\text{max\_val}[\text{root}_1], \text{max\_val}[\text{root}_2])\)
- Retrieving the Answers:
- For each city \(i\) (\(1 \le i \le N\)), find the root of the group containing \(i\), and output the
max_valstored at that root.
- For each city \(i\) (\(1 \le i \le N\)), find the root of the group containing \(i\), and output the
Complexity
- Time Complexity: \(O((N + M) \alpha(N))\)
- Here, \(\alpha\) is the inverse Ackermann function, which can be regarded as a constant of \(4\) or less in practice.
- By applying path compression and union by size to the Union-Find, each query (finding the root or merging) can be processed in nearly \(O(1)\) time.
- Under the constraints \(N, M \le 2 \times 10^5\), this will easily run well within the time limit.
- Space Complexity: \(O(N)\)
- We use arrays of size \(N + 1\) to maintain the parent nodes, group sizes, and the maximum value of each group.
Implementation Notes
Fast I/O: Since \(N\) and \(M\) can be as large as \(2 \times 10^5\), in Python, reading the entire input at once using
sys.stdin.read().split()and joining the output with\ncan significantly speed up execution.Handling Multiple Edges and Self-Loops: Although the problem constraints explicitly state that multiple edges and self-loops may exist, Union-Find does nothing when attempting to merge vertices that already share the same root, so they can be handled correctly without any special conditional branches.
Handling 1-based Indexing: Because the cities are numbered from \(1\) to \(N\), allocating arrays of size \(N + 1\) helps avoid indexing mistakes.
Source Code
import sys
def main():
input_data = sys.stdin.read().split()
if not input_data:
return
N = int(input_data[0])
M = int(input_data[1])
# A_1 から A_N までを 1-indexed で取得
max_val = [0] + [int(x) for x in input_data[2 : 2 + N]]
parent = list(range(N + 1))
size = [1] * (N + 1)
def find(i):
while i != parent[i]:
parent[i] = parent[parent[i]]
i = parent[i]
return i
def union(i, j):
root_i = find(i)
root_j = find(j)
if root_i != root_j:
if size[root_i] < size[root_j]:
root_i, root_j = root_j, root_i
parent[root_j] = root_i
size[root_i] += size[root_j]
if max_val[root_j] > max_val[root_i]:
max_val[root_i] = max_val[root_j]
idx = 2 + N
for _ in range(M):
u = int(input_data[idx])
v = int(input_data[idx + 1])
idx += 2
union(u, v)
ans = [str(max_val[find(i)]) for i in range(1, N + 1)]
sys.stdout.write("\n".join(ans) + "\n")
if __name__ == "__main__":
main()
This editorial was generated by gemini-3.8-flash-high.
posted:
last update: