Official

E - 伝言リレー / Message Relay Editorial by admin

gpt-5.5-high

Overview

If we view each student as a vertex and the passing destination \(P_i\) as a directed edge, we obtain a graph where the out-degree of each vertex is \(1\).
For each quiz, we want to quickly find “the first student whose ability is greater than or equal to the difficulty level when following \(P\) from the starting vertex before looping back.”

Analysis

A quiz of difficulty \(D_i\) distributed to student \(i\) is processed along the following sequence of students:

\[ i,\ P_i,\ P_{P_i},\ \ldots \]

However, the moment we try to pass it to an already visited student, the quiz becomes unanswered.
In other words, the sequence of students we need to check for each quiz is the sequence of unique vertices from the starting vertex up to right before we return to an already visited vertex for the first time.

For example, if the sequence of students from a starting vertex is

\[ 3 \rightarrow 5 \rightarrow 2 \rightarrow 4 \]

and we return to \(5\) next, we only check up to \(3, 5, 2, 4\).
Among these, the first student \(j\) satisfying \(S_j \geq D_i\) will be the answer.


If we naively simulate this for each quiz, we might traverse up to \(O(N)\) students per query.
Since there are \(N\) quizzes, the overall time complexity would be \(O(N^2)\), which is too slow for \(N \leq 2 \times 10^5\).

Therefore, we precompute the following two things:

  1. How many students can be checked from each starting vertex.
  2. Doubling (binary lifting) to quickly find the first position in the sequence where \(S_j \geq D_i\).

Since exactly one edge goes out from each vertex, each connected component always has the following structure:

  • A single directed cycle
  • Trees rooted at the cycle and directed towards it

In other words, if we follow the edges from any vertex, we will eventually enter a cycle.

Let \(L_v\) be the number of checkable students from the starting vertex \(v\):

  • If \(v\) is on the cycle:
    \(L_v = \) length of that cycle
  • If \(v\) is outside the cycle:
    \(L_v = \) distance to the cycle \(+\) length of the cycle

Algorithm

1. Finding Vertices on Cycles

First, we count the in-degree of each vertex.

Vertices with an in-degree of \(0\) cannot be part of any cycle.
If we remove such a vertex, the next vertices whose in-degrees become \(0\) are also not part of any cycle.

By repeating this process using a queue, only the vertices remaining at the end will be on cycles.

In the code, vertices with

removed[v] = True

are outside cycles, while those with removed[v] == False are on cycles.


2. Finding the Number of Checkable Students \(L_v\) for Each Vertex

For vertices on a cycle, we can find the cycle’s length by actually traversing it once.
If the cycle length is \(c\), we set

\[ L_v = c \]

for all vertices on that cycle.

Next, we propagate this to vertices outside the cycle using reversed edges.

Let \(v\) be the destination of vertex \(u\).
That is,

\[ P_u = v \]

In this case, the sequence checked from \(u\) consists of \(u\) followed by the sequence checked from \(v\).
Therefore,

\[ L_u = L_v + 1 \]

By propagating this outwards from the cycles using a BFS-like approach, we can determine \(L_v\) for all vertices.


3. Precomputing Range Maximums with Doubling

For each quiz, we want to find the first student satisfying

\[ S_j \geq D_i \]

while looking at at most \(L_i\) people from the starting vertex \(i\).

To speed this up, we use doubling.

We precompute the following:

  • jump[k][v]
    The vertex reached after passing \(2^k\) times from vertex \(v\)
  • mx[k][v]
    The maximum ability \(S\) among the \(2^k\) people starting from vertex \(v\)

The base cases are:

\[ jump[0][v] = P_v \]

\[ mx[0][v] = S_v \]

The transitions are:

\[ jump[k][v] = jump[k-1][jump[k-1][v]] \]

\[ mx[k][v] = \max(mx[k-1][v],\ mx[k-1][jump[k-1][v]]) \]


4. Answering Each Quiz

Let \(i\) be the starting vertex and \(x = D_i\) be the difficulty.

Set the current position to cur = i and the remaining checkable count to rem = L_i.

We iterate through \(k\) from largest to smallest:

  • If the remaining count is at least \(2^k\)
  • AND the maximum ability of the next \(2^k\) people is less than \(x\)

If both conditions are met, there is no student who can solve the quiz among these \(2^k\) people, so we can skip them all at once.

That is, we update:

cur = jump[k][cur]
rem -= 2^k

By repeating this, we can skip the longest prefix of students who are guaranteed to be unable to solve the quiz.

Finally:

  • If rem == 0, no checkable student could solve it, so the answer is -1.
  • Otherwise, the current position cur is the first student who can solve it, so the answer is cur + 1.

Complexity

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

Cycle detection and the calculation of \(L_v\) take \(O(N)\) time.
Since the precomputation for doubling takes \(O(N \log N)\) and answering each quiz takes \(O(\log N)\), the overall complexity is \(O(N \log N)\).

Implementation Points

  • The input is 1-indexed, but in the implementation, it is converted to 0-indexed for convenience.

  • limit[v] represents \(L_v\), which is the number of checkable people starting from vertex \(v\).

  • mx[k][v] is the maximum ability among the next \(2^k\) people.
    If this is less than the difficulty, we can skip the entire interval.

  • The visited information is independent for each quiz, but managing visited states for each quiz individually would be too slow.
    Instead, we precompute how many people we need to check from each starting vertex as limit.

    Source Code

import sys

def main():
    data = list(map(int, sys.stdin.buffer.read().split()))
    if not data:
        return

    n = data[0]
    idx = 1
    P = [x - 1 for x in data[idx:idx + n]]
    idx += n
    S = data[idx:idx + n]
    idx += n
    D = data[idx:idx + n]
    del data

    rev = [[] for _ in range(n)]
    indeg = [0] * n
    for i, p in enumerate(P):
        indeg[p] += 1
        rev[p].append(i)

    removed = [False] * n
    q = [i for i, d in enumerate(indeg) if d == 0]
    head = 0
    while head < len(q):
        v = q[head]
        head += 1
        removed[v] = True
        to = P[v]
        indeg[to] -= 1
        if indeg[to] == 0:
            q.append(to)

    limit = [0] * n

    for i in range(n):
        if not removed[i] and limit[i] == 0:
            cyc = []
            v = i
            while True:
                cyc.append(v)
                v = P[v]
                if v == i:
                    break
            l = len(cyc)
            for v in cyc:
                limit[v] = l

    q = [i for i in range(n) if not removed[i]]
    head = 0
    while head < len(q):
        v = q[head]
        head += 1
        nv = limit[v] + 1
        for u in rev[v]:
            if removed[u] and limit[u] == 0:
                limit[u] = nv
                q.append(u)

    LOG = n.bit_length()
    jump = [P]
    mx = [S]

    for _ in range(1, LOG):
        pj = jump[-1]
        pm = mx[-1]
        nj = [0] * n
        nm = [0] * n
        for v in range(n):
            mid = pj[v]
            nj[v] = pj[mid]
            a = pm[v]
            b = pm[mid]
            nm[v] = a if a >= b else b
        jump.append(nj)
        mx.append(nm)

    pows = [1 << k for k in range(LOG)]
    ans = [-1] * n

    for i, x in enumerate(D):
        cur = i
        rem = limit[i]
        for k in range(LOG - 1, -1, -1):
            if rem >= pows[k] and mx[k][cur] < x:
                rem -= pows[k]
                cur = jump[k][cur]
        if rem > 0 and S[cur] >= x:
            ans[i] = cur + 1

    print(' '.join(map(str, ans)))

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.5-high.