G - 地域の特産品 / Local Specialty Products Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
We divide the cities connected by roads into groups (connected components) and find the maximum value of the specialty products within each group. Using Union-Find, we can merge the groups of cities while maintaining the maximum values.
Analysis
Since the roads are bidirectional, cities belonging to the same connected component can reach each other. On the other hand, it is impossible to travel to cities in different connected components.
Therefore, the answer for all cities belonging to the same connected component is identical, which is the maximum value of \(A_i\) within that component.
For example, if cities \(1,2,3\) are connected by roads and their specialty product values are \(4,9,2\) respectively, the answers for all \(3\) cities are \(9\).
Running a DFS or BFS from each city would take \(O(N(N+M))\) time in the worst case, which will not pass within the time limit. This is because the same connected component would be traversed multiple times.
Thus, we manage connected components using Union-Find. By having the representative vertex (root) of each component store the maximum value within that component, we can merge components and update the maximum values simultaneously.
Algorithm
1. Initialization
Initially, each city forms an isolated connected component.
parent[i] = -1maximum[i] = A_i
parent is used as follows:
parent[i] < 0: City \(i\) is a root, and-parent[i]is the number of cities in the component.parent[i] >= 0:parent[i]is the vertex index of its parent.
For a root \(r\), maximum[r] represents the maximum value of the specialty products in that component.
2. Merging Components for Each Road
For the cities at both ends of each road, find their respective roots \(u,v\) using find.
- If \(u=v\), they already belong to the same component, so do nothing.
- If \(u\ne v\), attach the smaller component to the larger component.
Letting \(u\) be the root after the merge, update the values as follows:
parent[u] += parent[v]
parent[v] = u
maximum[u] = max(maximum[u], maximum[v])
The merged component is the union of the \(2\) components before merging. Therefore, the new maximum value is the larger of the maximum values of the two components.
3. Outputting the Answer for Each City
After processing all roads, output the following as the answer for city \(i\):
maximum[find(i)]
Every time a road is processed, the components containing its endpoints are merged, so the final groups in the Union-Find match the connected components formed by the roads. In addition, the maximum value at each root is correctly updated with each merge, yielding the desired answer.
Complexity
- Time Complexity: \(O((N+M)\alpha(N))\)
- Space Complexity: \(O(N+M)\)
\(\alpha(N)\) is the inverse Ackermann function, which is practically constant. Using union-by-size and path compression, Union-Find operations run very quickly.
While the Union-Find arrays themselves take \(O(N)\) space, this code reads the entire input at once, resulting in an overall space complexity of \(O(N+M)\).
Implementation Notes
Convert vertex indices to \(0\)-indexed
Since the city indices in the input are \(1\)-indexed, subtract \(1\) when storing and accessing them in arrays.Larger components have smaller
parentvalues
The root stores the negated number of cities. Ifparent[u] > parent[v], the component rooted at \(u\) is smaller, so swap them before merging.Only reference the maximum values at the roots
There is no need to updatemaximumfor vertices that are no longer roots. When retrieving the answer, always accessmaximum[find(i)].Rewire parents to grandparents in
find
Compressing the path while traversing to the root speeds up subsequent queries. Furthermore, using an iterative implementation avoids recursion depth issues.Handles multi-edges and self-loops naturally
By skipping the merge when both endpoints already share the same root, no special handling is required. Even when there are \(0\) roads, each city remains in its own component, so each city’s own \(A_i\) is output correctly.Source Code
import sys
def main():
data = iter(map(int, sys.stdin.buffer.read().split()))
n = next(data)
m = next(data)
maximum = [next(data) for _ in range(n)]
parent = [-1] * n
def find(x):
while parent[x] >= 0:
p = parent[x]
if parent[p] >= 0:
parent[x] = parent[p]
x = p
return x
for _ in range(m):
u = find(next(data) - 1)
v = find(next(data) - 1)
if u == v:
continue
if parent[u] > parent[v]:
u, v = v, u
parent[u] += parent[v]
parent[v] = u
if maximum[v] > maximum[u]:
maximum[u] = maximum[v]
sys.stdout.write("\n".join(str(maximum[find(i)]) for i in range(n)))
if __name__ == "__main__":
main()
This editorial was generated by gpt-6-astra-medium.
posted:
last update: