Official

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

gemini-3.5-flash-high

Overview

This problem asks us to simulate which student solves a quiz on a directed graph where each student points to the next student. A simple simulation would take \(O(N^2)\) time in the worst case. However, by utilizing the properties of the graph structure (Functional Graph) and doubling (binary lifting), we can process each query efficiently in \(O(\log N)\) time.

Analysis

1. Graph Structure and Termination Conditions

From each student \(i\), there is exactly one outgoing edge pointing to \(P_i\). Such a directed graph where every vertex has an out-degree of exactly 1 is called a Functional Graph. It consists of several “trees” and “cycles”. No matter which student you start from, repeating the transitions will always eventually lead to a cycle.

The simulation for a quiz terminates in either of the following cases: - When reaching a student who can solve the quiz (\(S_j \ge D_i\)). - When reaching an already visited student again (i.e., completing a full loop of a cycle).

2. Naive Approach and Its Limitations

If we simulate the process step-by-step starting from each student, in the worst case (for example, a straight path of length \(O(N)\) where no one can solve the quiz), a single simulation takes \(O(N)\) time. Doing this for all \(N\) students would result in an overall time complexity of \(O(N^2)\), which will exceed the time limit (TLE) under the constraint \(N \le 2 \times 10^5\).

3. Speed-up Idea

Let \(L_u\) be the maximum number of steps we can take starting from vertex \(u\) without visiting any vertex twice before the quiz is considered “unsolved”. If the distance from the starting vertex to the cycle is \(dist\_to\_cycle[u]\) and the cycle length is \(cycle\_len[u]\), we can make at most \(L_u = dist\_to\_cycle[u] + cycle\_len[u] - 1\) steps. If we take more steps than this, we will definitely visit a vertex in the cycle twice, and the game will terminate.

Therefore, the problem can be rephrased as: “Among the path of at most \(L_u\) steps starting from vertex \(u\), find the first vertex where the academic ability \(S\) is at least \(D_u\). If no such vertex exists, output \(-1\).”

This can be solved efficiently using doubling (binary lifting).

Algorithm

This problem can be solved in the following three steps:

Step 1: Cycle Detection and Computing Maximum Step Count \(L_u\)

We perform cycle detection for each vertex. By using DFS (Depth-First Search) or state management (e.g., visiting, visited), we can compute the following values for each vertex \(u\) in \(O(N)\) time: - \(dist\_to\_cycle[u]\): The number of steps to reach a cycle (0 if the vertex is already on a cycle). - \(cycle\_len[u]\): The length of the cycle reached.

Using these, we obtain the maximum steps we can take from each vertex \(u\): \(L_u = dist\_to\_cycle[u] + cycle\_len[u] - 1\).

Step 2: Constructing the Doubling Table

Using doubling, we construct the following two tables: - next_tbl[k][u]: The vertex reached after taking \(2^k\) steps from vertex \(u\). - max_S[k][u]: The maximum academic ability \(S\) among the students on the path of length \(2^k - 1\) steps starting from vertex \(u\) (including \(u\) itself).

These can be constructed in \(O(N \log N)\) time in the order of \(k = 0, 1, \dots, K-1\) using the following recurrence relations: - next_tbl[k][u] = next_tbl[k-1][next_tbl[k-1][u]] - max_S[k][u] = max(max_S[k-1][u], max_S[k-1][next_tbl[k-1][u]])

Note: \(K\) is the smallest integer satisfying \(2^K > N\) (since \(N \le 2 \times 10^5\), \(K = 18\) is sufficient).

Step 3: Query Processing

For each student \(u\), we search for the first student who satisfies the condition based on the quiz difficulty \(D_u\), in a manner similar to binary search. 1. Set the current vertex curr = u and the remaining steps rem = L[u]. 2. Loop \(k\) from \(K-1, K-2, \dots, 0\). 3. If \(2^k \le rem\) and the maximum academic ability during the \(2^k\) steps from curr (max_S[k][curr]) is strictly less than \(D_u\), then there is no student satisfying the condition in this range. Therefore, we can jump \(2^k\) steps forward at once: - curr = next_tbl[k][curr] - rem -= 2^k 4. After the loop ends, curr will be “the student immediately before the academic ability becomes \(D_u\) or greater” or “the student reached after taking the maximum possible steps”. 5. If \(S_{curr} \ge D_u\), then curr is the student who ultimately solves the quiz. 6. Otherwise, no such student exists, so the result is \(-1\).

Complexity

  • Time Complexity: \(O(N \log N)\)
    • Cycle detection and computing \(L_u\) takes \(O(N)\) time, constructing the doubling tables takes \(O(N \log N)\) time, and processing each query takes \(O(\log N)\) time. Thus, the overall time complexity is \(O(N \log N)\), which easily runs within the time limit.
  • Space Complexity: \(O(N \log N)\)
    • The sizes of the doubling tables next_tbl and max_S are \(O(N \log N)\), which becomes the bottleneck of the space complexity.

Implementation Details

  • 1-indexed Conversion: Since the student indices are from \(1\) to \(N\), adding a dummy element (0) at the beginning of the arrays to process them with 1-based indexing helps prevent index mismatch errors.

  • Avoiding Recursion: Using recursive functions for cycle detection in languages like Python can cause the program to reach the maximum recursion depth limit or introduce large overhead. It is safer to implement cycle detection non-recursively using loops, as in the presented code.

  • Doubling Transition Range: max_S[k][u] stores the maximum academic ability of \(2^k\) vertices starting from \(u\) (including \(u\) itself). During the doubling update, taking the maximum of max_S[k-1][u] and max_S[k-1][next_tbl[k-1][u]] correctly covers the interval of size \(2^k\).

    Source Code

import sys

def solve():
    # Fast I/O
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    
    N = int(input_data[0])
    P = [0] + [int(x) for x in input_data[1:N+1]]
    S = [0] + [int(x) for x in input_data[N+1:2*N+1]]
    D = [0] + [int(x) for x in input_data[2*N+1:3*N+1]]
    
    # Cycle detection and calculating maximum safe step limits (L_u)
    state = [0] * (N + 1)
    dist_to_cycle = [-1] * (N + 1)
    cycle_len = [-1] * (N + 1)
    
    for i in range(1, N + 1):
        if state[i] != 0:
            continue
        curr = i
        path = []
        while state[curr] == 0:
            state[curr] = 1
            path.append(curr)
            curr = P[curr]
        
        if state[curr] == 1:
            idx = path.index(curr)
            cycle_nodes = path[idx:]
            clen = len(cycle_nodes)
            for node in cycle_nodes:
                cycle_len[node] = clen
                dist_to_cycle[node] = 0
                state[node] = 2
            for j in range(idx - 1, -1, -1):
                node = path[j]
                nxt = P[node]
                dist_to_cycle[node] = dist_to_cycle[nxt] + 1
                cycle_len[node] = cycle_len[nxt]
                state[node] = 2
        else:
            for j in range(len(path) - 1, -1, -1):
                node = path[j]
                nxt = P[node]
                dist_to_cycle[node] = dist_to_cycle[nxt] + 1
                cycle_len[node] = cycle_len[nxt]
                state[node] = 2
                
    L = [dist_to_cycle[i] + cycle_len[i] - 1 for i in range(N + 1)]
    
    # Doubling table construction
    K = 18
    next_tbl = [[0] * (N + 1) for _ in range(K)]
    max_S = [[0] * (N + 1) for _ in range(K)]
    
    next_tbl[0] = P[:]
    max_S[0] = S[:]
    
    for k in range(1, K):
        prev_next = next_tbl[k-1]
        prev_max = max_S[k-1]
        curr_next = next_tbl[k]
        curr_max = max_S[k]
        for u in range(1, N + 1):
            nxt = prev_next[u]
            curr_next[u] = prev_next[nxt]
            val1 = prev_max[u]
            val2 = prev_max[nxt]
            curr_max[u] = val1 if val1 > val2 else val2
            
    steps = [1 << k for k in range(K)]
    ans = [0] * N
    
    # Query processing
    for u in range(1, N + 1):
        curr = u
        rem = L[u]
        du = D[u]
        
        for k in range(K - 1, -1, -1):
            step = steps[k]
            if step <= rem:
                if max_S[k][curr] < du:
                    curr = next_tbl[k][curr]
                    rem -= step
                    
        if S[curr] >= du:
            ans[u-1] = curr
        else:
            ans[u-1] = -1
            
    print(*(ans))

if __name__ == '__main__':
    solve()

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

posted:
last update: