Official

E - 循環搬送網の回収口 / Collection Port of a Circular Conveyor Network Editorial by admin Editorial for printing

Gemini 3.8 Flash (High)

Overview

This problem asks us to find the maximum possible sum of \((\text{distance} \times \text{luggage amount})\) from all vertices that can reach a chosen collection point, in a directed graph where every vertex has an out-degree of \(1\) (a functional graph / Namori graph).

By aggregating the information from the tree components from the leaves toward the cycles, and using differential updates for vertices on the cycles, this problem can be solved in \(O(N)\).


Analysis

1. Structural Properties of the Graph

Since every platform has exactly \(1\) predetermined destination, this directed graph is partitioned into several weakly connected components, each consisting of “a single directed cycle” and “directed trees feeding into that cycle”.

In such a graph, choosing a vertex as the collection point falls into one of two main cases:

  1. When a vertex outside the cycle (in a tree component) is chosen as the collection point
    • Only the luggage in the subtree directed into that vertex (the subtree when viewing edges in reverse) can reach the collection point.
  2. When a vertex on the cycle is chosen as the collection point
    • Luggage from all vertices on the cycle, as well as all trees feeding into that cycle, can reach the collection point.

2. Naive Approach and Its Limitations

If we simulate choosing each vertex as the collection point individually, finding the distances using reverse BFS or DFS takes \(O(N)\) per vertex. This results in an overall time complexity of \(O(N^2)\), which will exceed the time limit (TLE) under the constraint \(N \leq 200000\).

3. Key Idea

We decompose the problem into the “tree components” and the “cycle components”.

① Processing Tree Components (Bottom-up Aggregation)

We aggregate information starting from vertices with an in-degree of \(0\) (the leaves of the trees) toward the cycle. For each vertex \(u\), we maintain the following values: - \(W_u\): Total amount of luggage flowing into vertex \(u\) (initially \(A_u\)) - \(D_u\): Total score within its subtree when vertex \(u\) is chosen as the collection point

When moving from vertex \(u\) to its parent \(p = P_u\), all luggage is transported to the parent. Since the distance increases by \(1\), the contribution to the parent can be updated using the following equations: $\(W_p \leftarrow W_p + W_u\)\( \)\(D_p \leftarrow D_p + (D_u + W_u)\)$

If a tree vertex \(u\) is chosen as the collection point, the score is simply \(D_u\).

② Processing Cycle Components (Differential Updates)

After fully contracting the tree components, only vertices on the cycles remain. Let a cycle be \(C_0 \to C_1 \to \dots \to C_{k-1} \to C_0\) (of length \(k\)). Each vertex \(C_j\) holds the total luggage from its incoming tree \(S_j = W_{C_j}\) and the internal tree score \(E_j = D_{C_j}\).

When a vertex on the cycle is chosen as the collection point, the sum of internal tree scores \(\sum_{j=0}^{k-1} E_j\) is the same regardless of which cycle vertex is chosen. What changes is only the score from the number of steps moved along the cycle.

  • When \(C_0\) is chosen as the collection point: The distance from vertex \(C_j\) to \(C_0\) is \((k - j) \bmod k\). Therefore, the score from moving along the cycle, \(f(C_0)\), is: $\(f(C_0) = \sum_{j=0}^{k-1} S_j \times ((k - j) \bmod k)\)$

  • When the collection point shifts from \(C_j\) to the next vertex \(C_{j+1}\): When advancing the collection point by \(1\) vertex, the distance from each vertex changes as follows:

    • Luggage at \(C_{j+1}\): The distance changes from \(k - 1\) to \(0\) (a change of \(-(k - 1)\))
    • Luggage at all other vertices: The distance increases by \(1\) (a change of \(+1\))

Letting the total luggage on the entire cycle be \(TotalS = \sum_{m=0}^{k-1} S_m\), the difference in score can be calculated in one step as follows: $\(\Delta = (TotalS - S_{j+1}) \times 1 - S_{j+1} \times (k - 1) = TotalS - k \times S_{j+1}\)\( Using this, after computing the initial score for \)1\( vertex in \)O(k)\(, the scores when other vertices on the cycle are chosen as the collection point can be computed sequentially in \)O(1)$ per vertex using differential updates.


Algorithm

  1. In-degree Management and Topological Sort:

    • Compute the in-degree of each vertex and push vertices with an in-degree of \(0\) into a queue.
    • Pop vertex \(u\) from the queue, and update the luggage amount \(W\) and score \(D\) for its parent \(p = P_u\).
    • Record \(D_u\) as a candidate answer at each step, representing the score if tree vertex \(u\) is chosen as the collection point.
    • Decrement the in-degree of \(p\), and push it to the queue if it becomes \(0\).
  2. Cycle Extraction and Score Calculation:

    • Vertices that still have an in-degree of \(1\) or more belong to cycles. Traverse and extract each cycle from unvisited vertices.
    • Compute the sum of internal tree scores \(\sum E\) across all vertices in the cycle, and the cycle movement score \(f(C_0)\) for the base vertex (\(C_0\)).
    • Using the differential update formula, shift the collection point through \(C_0, C_1, \ldots, C_{k-1}\) and update the maximum score \(\sum E + f(C_j)\).

Complexity

  • Time Complexity: \(O(N)\)
    • Aggregating the tree components via topological sort visits each vertex and edge once, taking \(O(N)\) time.
    • Cycle detection and differential updates on each cycle also visit each cycle vertex at most a constant number of times, taking \(O(N)\) in total.
  • Space Complexity: \(O(N)\)
    • Uses \(O(N)\) memory for the graph transition array \(P\), in-degree array, weight/score tracking arrays, etc.

Implementation Notes

  • Preventing Overflow: The maximum score can reach approximately \(N \times \max(A) \times N \approx 2 \times 10^5 \times 10^6 \times 2 \times 10^5 = 4 \times 10^{16}\) in the worst case (such as a path of length \(N\) carrying a large amount of luggage). Since this overflows a 32-bit integer, be sure to use a 64-bit integer type (such as long long in C++) for luggage amounts and score calculations.

  • Handling Self-loops: Self-loops where \(P_i = i\) (cycles of length \(1\)) may exist, but the algorithm correctly handles them with the exact same logic as a cycle of length \(k = 1\).

    Source Code

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int N;
    if (!(cin >> N)) return 0;

    vector<int> P(N + 1);
    vector<int> deg(N + 1, 0);
    for (int i = 1; i <= N; ++i) {
        cin >> P[i];
        deg[P[i]]++;
    }

    vector<long long> A(N + 1);
    for (int i = 1; i <= N; ++i) {
        cin >> A[i];
    }

    vector<long long> W = A;
    vector<long long> D(N + 1, 0);

    queue<int> q;
    for (int i = 1; i <= N; ++i) {
        if (deg[i] == 0) {
            q.push(i);
        }
    }

    long long ans = 0;

    while (!q.empty()) {
        int u = q.front();
        q.pop();

        ans = max(ans, D[u]);

        int p = P[u];
        W[p] += W[u];
        D[p] += D[u] + W[u];

        deg[p]--;
        if (deg[p] == 0) {
            q.push(p);
        }
    }

    vector<bool> visited(N + 1, false);
    for (int i = 1; i <= N; ++i) {
        if (deg[i] > 0 && !visited[i]) {
            vector<int> cycle;
            int curr = i;
            while (!visited[curr]) {
                visited[curr] = true;
                cycle.push_back(curr);
                curr = P[curr];
            }

            int k = cycle.size();
            vector<long long> S(k), E(k);
            long long sumE = 0;
            long long TotalS = 0;
            for (int j = 0; j < k; ++j) {
                int node = cycle[j];
                S[j] = W[node];
                E[j] = D[node];
                sumE += E[j];
                TotalS += S[j];
            }

            long long cur_f = 0;
            for (int j = 0; j < k; ++j) {
                cur_f += S[j] * ((k - j) % k);
            }

            for (int j = 0; j < k; ++j) {
                ans = max(ans, sumE + cur_f);
                if (j + 1 < k) {
                    cur_f = cur_f + TotalS - (long long)k * S[j + 1];
                }
            }
        }
    }

    cout << ans << "\n";

    return 0;
}

This editorial was generated by gemini-3.8-flash-high.

posted:
last update: