Official

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

gpt-6-astra-medium

Overview

In a graph where each conveyor platform is a vertex and each destination is a directed edge, we want to maximize the sum of (number of items \(\times\) number of moves) for all items that reach the collection point.

By decomposing the graph into “cycles” and “trees flowing into them,” and processing the tree parts with dynamic programming and the cycle parts with differential updates, the problem can be solved in \(O(N)\) overall time.

Analysis

1. The Graph Consists of Cycles and Trees

We place a directed edge from conveyor platform \(i\) to \(P_i\). Since every vertex has an out-degree of exactly \(1\), no matter which vertex we start from, continuing to move will eventually revisit a vertex and enter a cycle.

Therefore, each connected component of the graph has the following structure:

  • There is exactly \(1\) directed cycle.
  • Vertices flow into each vertex on the cycle in a tree-like structure.

An edge to oneself (a self-loop) is also a cycle of length \(1\).

If the collection point is outside a cycle, only the items in the tree flowing into that vertex are collected. On the other hand, if the collection point is on a cycle, all items in the same connected component are collected.

2. Searching for Each Collection Point Individually is Too Slow

If we fix one collection point, we can trace edges in reverse to find all reachable vertices and their number of moves in \(O(N)\) time.

However, doing this for all candidate collection points would take \(O(N^2)\) time, which is too slow for \(N \leq 200000\).

Instead, we aggregate the computation results of the tree parts and pass them to their destinations, and on the cycles, we only compute the change in score as the collection point is shifted.

3. Tree Items Can Be Aggregated by “Count” and “Sum of Distances”

For each vertex \(u\), we maintain the following values:

  • weight[u]: the total number of items aggregated at \(u\)
  • dist[u]: the sum of the number of moves those items make from their initial positions to \(u\)

The initial values are weight[u] \(=A_u\) and dist[u] \(=0\).

When the items aggregated at \(u\) are moved one step further to their destination \(v=P_u\), the number of moves for every item increases by \(1\). Therefore, we can update as follows:

  • dist[v] \(\mathrel{+}=\) dist[u] \(+\) weight[u]
  • weight[v] \(\mathrel{+}=\) weight[u]

By doing this in order starting from the leaves of the trees, there is no need to traverse the same components multiple times.

Algorithm

1. Process the Tree Parts Starting from Vertices with In-degree \(0\)

Calculate the in-degree of each vertex and push all vertices with in-degree \(0\) into a queue.

Each time a vertex \(u\) is popped from the queue, perform the following:

  1. Update the maximum answer with dist[u].
  2. Add to weight and dist of \(v=P_u\) using the formulas above.
  3. Decrement the in-degree of \(v\) by \(1\); if it becomes \(0\), push \(v\) into the queue.

At the moment \(u\) is popped from the queue, all vertices flowing into \(u\) have already been processed. Therefore, dist[u] is the exact score obtained when choosing \(u\) as the collection point.

Through this process, all vertices outside cycles are removed, leaving only vertices on the cycles.

In addition, for each vertex \(v\) on a cycle, the following information has been accumulated:

  • weight[v]: the total number of items that enter the cycle at \(v\), including items initially at \(v\).
  • dist[v]: the sum of the number of moves for those items to reach \(v\).

2. For Each Cycle, Compute the Score for the First Collection Point

Starting from any remaining vertex, follow the destinations to extract the cycle.

List the vertices of the cycle along the direction of the edges as:

\(c_0 \to c_1 \to \cdots \to c_{L-1} \to c_0\)

Also, let:

\(W_i=\mathrm{weight}[c_i]\), \(D_i=\mathrm{dist}[c_i]\)

First, find the score \(S_0\) when \(c_0\) is chosen as the collection point.

Moving through the tree parts contributes a total of \(\sum_{i=0}^{L-1}D_i\) moves across all items. Furthermore, the distance on the cycle from \(c_i\) to \(c_0\) is \(L-i\) when \(i>0\).

Therefore,

\(S_0=\displaystyle\sum_{i=0}^{L-1}D_i+\sum_{i=1}^{L-1}W_i(L-i)\)

For example, in a cycle of length \(3\): \(c_0 \to c_1 \to c_2 \to c_0\), the distances to \(c_0\) are \(0, 2, 1\) respectively, so:

\(S_0=D_0+D_1+D_2+2W_1+W_2\)

3. Shift the Collection Point and Update the Score Differentially

Let the total number of items in the cycle component be:

\(T=\displaystyle\sum_{i=0}^{L-1}W_i\)

When moving the collection point from \(c_{i-1}\) to the next vertex \(c_i\), the number of moves along the cycle changes as follows:

  • For items entering the cycle from vertices other than \(c_i\), their number of moves increases by \(1\).
  • For items entering the cycle from \(c_i\), their number of moves decreases by \(L-1\) (changing from \(L-1\) to \(0\)).

The number of moves within the tree parts does not change. Therefore, the change in score is:

\((T-W_i)-(L-1)W_i=T-LW_i\)

Consequently,

\(S_i=S_{i-1}+T-LW_i\)

allows us to compute the score for the next collection point in \(O(1)\) time.

Update this in the order \(i=1,2,\ldots,L-1\), and update the overall maximum answer with each score.

4. Output the Maximum Over All Candidates

With the steps above, we can evaluate the score for choosing each vertex as the collection point:

  • For vertices outside cycles: when they are processed by the queue
  • For vertices on cycles: during the computation for each cycle

The maximum value among all of them is the answer.

Complexity

  • Time Complexity: \(O(N)\)
  • Space Complexity: \(O(N)\)

Each vertex is processed a constant number of times during either tree processing or cycle processing.

Implementation Notes

  • Use 64-bit integers for the scores.
    Collected items will not revisit the same vertex before reaching the collection point for the first time, so the number of moves is at most \(N-1\). The total score can be up to around \(N \times 10^6 \times (N-1)\), which does not fit in a 32-bit integer. Use long long for weight, dist, scores, etc.

  • Evaluate the score of a tree vertex before passing its information to its destination.
    dist[u] at this point is the score when \(u\) is chosen as the collection point.

  • The in-degree array can also be reused to track visited vertices in cycles.
    After removing the trees, only vertices with positive in-degrees remain on the cycles. In the implementation, setting the in-degrees of vertices in an extracted cycle to \(0\) prevents the same cycle from being processed again.

  • Cycles of length \(1\) can be handled with the exact same logic.
    Since no moves along the cycle are necessary, the score is simply dist of that vertex.

    Source Code

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

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

    int N;
    cin >> N;

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

    vector<long long> weight(N), dist(N, 0);
    for (auto& x : weight) cin >> x;

    vector<int> que;
    que.reserve(N);
    for (int i = 0; i < N; ++i) {
        if (indegree[i] == 0) que.push_back(i);
    }

    long long answer = 0;
    for (size_t head = 0; head < que.size(); ++head) {
        int u = que[head];
        answer = max(answer, dist[u]);

        int v = P[u];
        dist[v] += dist[u] + weight[u];
        weight[v] += weight[u];

        if (--indegree[v] == 0) que.push_back(v);
    }

    vector<int> cycle;
    for (int start = 0; start < N; ++start) {
        if (indegree[start] == 0) continue;

        cycle.clear();
        int u = start;
        do {
            cycle.push_back(u);
            indegree[u] = 0;
            u = P[u];
        } while (u != start);

        long long length = static_cast<long long>(cycle.size());
        long long totalWeight = 0;
        long long score = 0;

        for (int i = 0; i < static_cast<int>(cycle.size()); ++i) {
            int v = cycle[i];
            totalWeight += weight[v];
            score += dist[v];
            if (i > 0) score += weight[v] * (length - i);
        }

        answer = max(answer, score);
        for (int i = 1; i < static_cast<int>(cycle.size()); ++i) {
            score += totalWeight - length * weight[cycle[i]];
            answer = max(answer, score);
        }
    }

    cout << answer << '\n';
    return 0;
}

This editorial was generated by gpt-6-astra-medium.

posted:
last update: