公式

G - 地域の特産品 / Local Specialty Products 解説 by admin

Claude Opus 5 (High)

Overview

This problem asks us to find, for each vertex in an undirected graph, the maximum weight of a vertex (the value of the specialty) within the connected component to which that vertex belongs. This can be solved by finding the connected components using Union-Find (Disjoint Set Union) or BFS/DFS and determining the maximum value for each component.

Analysis

Key Observation

The relation “it is possible to travel from city \(u\) to city \(v\)” is equivalent to belonging to the same connected component in an undirected graph. Since roads can be traversed in both directions in an undirected graph, the following properties hold:

  • Travel from \(u\) to \(u\) is possible (using \(0\) roads).
  • If travel from \(u\) to \(v\) is possible, travel from \(v\) to \(u\) is also possible.
  • If travel from \(u \to v\) and \(v \to w\) is possible, travel from \(u \to w\) is also possible.

In other words, “reachability” is an equivalence relation, and the set of all cities is partitioned into groups (connected components) that can reach one another.

Therefore, the answer is the same for all cities belonging to the same connected component (namely, the maximum \(A_i\) within that component).

Issues with the Naive Approach

The first method that comes to mind might be to perform a BFS or DFS starting from each city \(i\) to find the maximum \(A\) among the reachable cities. However, each search takes \(O(N+M)\), and repeating this for all \(N\) cities results in a time complexity of \(O(N(N+M))\). For \(N, M \le 2 \times 10^5\), this requires on the order of \(10^{10}\) operations, which will definitely result in TLE (Time Limit Exceeded).

Solution

From the observation above, the answer is identical for each connected component. Therefore, we can:

  1. First, find all connected components in a single pass.
  2. Compute the maximum value for each component.
  3. For each city, output the maximum value of its component.

Using Union-Find is a straightforward way to find the connected components, and running BFS/DFS starting from unvisited vertices also takes only \(O(N+M)\).

As a concrete example, suppose \(N=5\), \(A = (3, 7, 2, 9, 5)\), and the roads are \((1,2), (2,3), (4,5)\). The connected components are \(\{1,2,3\}\) and \(\{4,5\}\). The maximum value of the former is \(7\), and the latter is \(9\), so the answers are \(7, 7, 7, 9, 9\) in order.

Algorithm

Approach using Union-Find (DSU)

  1. Prepare a Union-Find data structure with \(N\) elements.
  2. For each road \((U_j, V_j)\), call unite(U_j, V_j). This merges reachable cities into the same group.
    • Multiple edges are not an issue because subsequent unite calls simply do nothing.
    • Self-loops \(U_j = V_j\) are also harmless, as find returns the same root and does nothing.
  3. Prepare an array mx, and for each city \(i\), let \(r = \mathrm{find}(i)\) and update mx[r] = max(mx[r], A[i]). This stores the maximum value within each group at its representative (root).
  4. For each city \(i\), output mx[find(i)].

Approach using BFS/DFS (Alternative Solution)

Prepare a visited array. Starting a BFS/DFS from an unvisited vertex \(s\), collect all reached vertices into a list, compute the maximum \(A\) among the vertices in that list, and assign that value as the answer for all vertices in the list. Since each vertex is visited only once, the total time complexity is \(O(N+M)\).

Union-Find runs in nearly constant time when implementing both path compression and union by size (or rank). In the code above, a single-array implementation is used where if p[x] is negative, \(x\) is a root whose size is given by its absolute value, and if non-negative, it points to the parent.

Complexity

  • Time Complexity: \(O(N + M \alpha(N))\) (\(\alpha\) is the inverse Ackermann function, which is practically constant. Thus, it is effectively \(O(N+M)\))
  • Space Complexity: \(O(N + M)\) (The Union-Find array takes \(O(N)\); if edge inputs are processed on the fly without storing the graph, additional space is \(O(1)\))

Implementation Points

  • 1-indexed / 0-indexed Conversion: The city numbers in the input are 1-indexed, so if you use 0-indexed arrays, convert them to u-1, v-1.

  • Multiple Edges and Self-loops: With Union-Find, no special handling is required at all. For BFS/DFS, the visited checks naturally handle them without issues.

  • Remember to Separate Component Aggregation: It is safe to separate the step of “aggregating maximum values at the roots” from the step of “calling find for each vertex to read the result.” Reading values while mx is still being updated may lead to reading values that have not been fully aggregated.

  • Initial Value of \(0\) is Sufficient Since \(A_i \ge 1\): If the initial values of the maximum are set to \(0\), they will always be overwritten by each city’s own \(A_i\) (in problems where \(A_i\) can be negative, use a value corresponding to \(-\infty\)).

  • Fast I/O: Since \(N, M\) are around \(2\times 10^5\), in C++ it is advisable to use scanf/printf or untie cin (ios::sync_with_stdio(false)). In the code above, the output is buffered into a string and written all at once using fwrite, which is faster than per-line printf. In Python, use sys.stdin.buffer.read() for bulk reading and sys.stdout.write("\n".join(...)) for bulk writing.

  • When \(M = 0\): No road lines are provided, which is naturally handled as the loop simply executes 0 times. Every city is isolated, so each answer is simply \(A_i\) itself.

    Source Code

#include <bits/stdc++.h>
using namespace std;

struct DSU {
    vector<int> p;
    DSU(int n): p(n, -1) {}
    int find(int x){ while(p[x] >= 0){ if(p[p[x]] >= 0) p[x] = p[p[x]]; x = p[x]; } return x; }
    void unite(int a, int b){
        a = find(a); b = find(b);
        if(a == b) return;
        if(p[a] > p[b]) swap(a, b);
        p[a] += p[b];
        p[b] = a;
    }
};

int main(){
    int N, M;
    if(scanf("%d %d", &N, &M) != 2) return 0;
    vector<int> A(N);
    for(int i = 0; i < N; i++) scanf("%d", &A[i]);
    DSU dsu(N);
    for(int j = 0; j < M; j++){
        int u, v; scanf("%d %d", &u, &v);
        dsu.unite(u-1, v-1);
    }
    vector<int> mx(N, 0);
    for(int i = 0; i < N; i++){
        int r = dsu.find(i);
        mx[r] = max(mx[r], A[i]);
    }
    string out;
    out.reserve(N * 11);
    char buf[16];
    for(int i = 0; i < N; i++){
        int len = snprintf(buf, sizeof(buf), "%d\n", mx[dsu.find(i)]);
        out.append(buf, len);
    }
    fwrite(out.data(), 1, out.size(), stdout);
    return 0;
}

This editorial was generated by claude5opus-high.