Official

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

gpt-6-astra-medium

Overview

Consider a graph where each platform is a vertex and moving to the destination is a directed edge. By aggregating the luggage outside the cycles and computing the score differences as we move the collection point along each cycle, the problem can be solved in \(O(N)\) overall.

Analysis

1. The graph consists of “cycles and trees flowing into them”

Draw a directed edge from vertex \(i\) to vertex \(P_i\).

Since each vertex has an out-degree of exactly \(1\), no matter which vertex we start from, we will eventually revisit a vertex and enter a cycle. Therefore, each connected component of the graph has the following structure:

  • A directed cycle at the center.
  • Tree-structured components flowing into each vertex of the cycle.

A vertex whose destination is itself is also a cycle of length \(1\).

2. We only need to consider collection points on a cycle

Consider the case where a vertex \(u\) not on a cycle is chosen as the collection point. If we move the collection point to its destination \(P_u\), all luggage that previously reached \(u\) will be collected after one additional move.

Here, this luggage never passes through \(P_u\) before reaching \(u\). If it did, there would be a cycle from \(P_u\) through \(u\) back to \(P_u\), which contradicts the fact that \(u\) is outside the cycle.

Therefore, the score from luggage that was already collected increases. Furthermore, even if there is newly collected luggage, its contribution is non-negative.

Hence, moving the collection point to the destination does not decrease the score. Repeating this process eventually leads to a cycle, so the maximum score is always achieved at a vertex on a cycle.

3. Aggregating parts outside the cycles

Even if we restrict the candidate collection points to the cycles, calculating the distance from all vertices for each candidate would take \(O(N^2)\) in the worst case, which is too slow.

Therefore, we aggregate the luggage outside the cycles into the first cycle vertex it reaches. For each cycle vertex \(v\), it is sufficient to know the following information:

  • weight[v]: The total number of pieces of luggage that reach \(v\) first, including the luggage initially at \(v\).
  • distance_sum[v]: The sum of the number of moves for those pieces of luggage to reach \(v\).

No matter which vertex on the cycle is chosen as the collection point, the number of moves made before entering the cycle remains the same. All that remains is to consider the number of moves on the cycle.

Algorithm

1. Aggregate luggage starting from vertices with in-degree \(0\)

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

The initial values are as follows:

  • weight[u] \(= A_u\)
  • distance_sum[u] \(= 0\)

Let \(u\) be the vertex popped from the queue, and let its destination be \(v=P_u\).

When moving the luggage aggregated at \(u\) to \(v\), every piece of luggage moves one more time, so we update as follows:

  • distance_sum[v] += distance_sum[u] + weight[u]
  • weight[v] += weight[u]

After that, consider the edge \(u \to v\) removed and decrement the in-degree of \(v\) by \(1\); if it becomes \(0\), add it to the queue.

Through this process, all vertices outside the cycles are removed, and the vertices whose in-degrees remain positive are the vertices on the cycles. In addition, the information about the luggage flowing into each cycle vertex has been aggregated into it.

2. Compute the score for the first collection point on a cycle

Trace the destinations from the remaining vertices to extract the cycles one by one.

Along the direction of the edges, let a cycle be

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

Also, let \(W_i=\texttt{weight}[c_i]\) and \(D_i=\texttt{distance\_sum}[c_i]\).

When placing the collection point at \(c_0\), the distance on the cycle from \(c_i\) to \(c_0\) is \(0\) if \(i=0\), and \(L-i\) if \(i\geq 1\).

Therefore, the score \(S_0\) can be calculated with the following formula:

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

For example, in a cycle of length \(3\), it takes \(2\) moves from \(c_1\) to \(c_0\), and \(1\) move from \(c_2\) to \(c_0\), so

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

3. Compute the difference when moving the collection point

Let the total amount of luggage aggregated into the cycle be

\(T=\displaystyle\sum_{j=0}^{L-1}W_j\)

Consider moving the collection point from \(c_{i-1}\) to \(c_i\).

  • For luggage other than that aggregated at \(c_i\), the number of moves on the cycle increases by \(1\).
  • For luggage aggregated at \(c_i\), the number of moves on the cycle changes from \(L-1\) to \(0\).

Thus, the change in score is

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

That is,

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

which allows us to compute the next score in \(O(1)\).

Using this formula, check the score when each vertex on the cycle is chosen as the collection point, and update the maximum value.

Luggage in other connected components cannot reach this collection point, so it is not included in the score. Process all cycles in the same way, and output the maximum value overall.

Complexity

  • Time complexity: \(O(N)\)
    Each vertex outside the cycles is processed once, and each vertex on the cycles is also processed a constant number of times.
  • Space complexity: \(O(N)\)
    To store the in-degrees, aggregated luggage counts, sum of moves, queue, etc.

Implementation Notes

  • Pay attention to the order of updates during aggregation.
    To distance_sum[v], add the extra move for each of the weight[u] pieces of luggage aggregated at the source vertex.

  • In the code, a Python list is used as a queue.
    Elements appended to the end during for u in queue: are processed in order. There is no need to remove elements from the front.

  • In-degrees are also used to keep track of visited vertices on the cycles.
    Setting indegree[u] = 0 when traversing a cycle prevents processing the same cycle multiple times.

  • Cycles of length \(1\) can be handled with the exact same logic.
    Since the number of moves on the cycle is \(0\), the score is simply distance_sum of that vertex.

  • Large integers are required for the score.
    Since each collected piece of luggage moves at most \(N-1\) times, the score can be up to \(10^6N(N-1)\). Python handles arbitrarily large integers natively, but in other languages, use \(64\)-bit integers.

    Source Code

import sys


def main():
    input = sys.stdin.buffer.readline
    n = int(input())
    p = [int(x) - 1 for x in input().split()]
    weight = list(map(int, input().split()))

    indegree = [0] * n
    for v in p:
        indegree[v] += 1

    distance_sum = [0] * n
    queue = [i for i in range(n) if indegree[i] == 0]

    for u in queue:
        v = p[u]
        distance_sum[v] += distance_sum[u] + weight[u]
        weight[v] += weight[u]
        indegree[v] -= 1
        if indegree[v] == 0:
            queue.append(v)

    answer = 0

    for start in range(n):
        if indegree[start] == 0:
            continue

        cycle_weights = []
        total_weight = 0
        score = 0
        u = start

        while indegree[u]:
            indegree[u] = 0
            w = weight[u]
            cycle_weights.append(w)
            total_weight += w
            score += distance_sum[u]
            u = p[u]

        length = len(cycle_weights)
        for i in range(1, length):
            score += (length - i) * cycle_weights[i]

        if score > answer:
            answer = score

        for i in range(1, length):
            score += total_weight - length * cycle_weights[i]
            if score > answer:
                answer = score

    print(answer)


if __name__ == "__main__":
    main()

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