Official

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

claude4.8opus-high

Overview

Since each student has exactly one designated person to pass the quiz to next, the quiz starts from a certain student and follows a single path. For each quiz, the problem asks us to find the first student who can solve it (\(S_j \geq D_i\)) by following the path from the starting point.

Analysis

Graph Structure

Each student \(i\) has exactly one next recipient \(P_i\). This is a graph where the out-degree of each vertex is exactly one (functional graph), and its structure always consists of “several trees attached to cycles” (rho-shaped).

Processing quiz \(i\) follows a single path \(i \to P_i \to P_{P_i} \to \cdots\), and:

  • If a student \(j\) with \(S_j \geq D_i\) appears along the way, that student solves it (the first such student to appear).
  • If we return to an already visited student (entering a cycle and completing a loop), the quiz remains unsolved, resulting in \(-1\).

Naive Approach and Its Issues

If we naively follow the path for each quiz, it takes \(O(N)\) in the worst case per query, resulting in \(O(N^2)\) overall. This will not run in time for \(N \leq 2 \times 10^5\) (TLE).

Optimization Strategy

There are two key points:

  1. Determining if the quiz can be solved at all (whether it is \(-1\))
    Let \(\mathrm{maxReach}[i]\) be the maximum value of \(S\) among all students reachable from student \(i\). If \(\mathrm{maxReach}[i] < D_i\), no one along the path can solve it, so the answer is \(-1\).

  2. Finding the first student who can solve it quickly
    Instead of moving along the path step-by-step, we can jump in bulk using doubling (binary lifting). If we know that “none of the next \(2^k\) students can solve it”, we can skip them all at once.

Algorithm

Step 1: Calculating maxReach

On the functional graph, we find the maximum value of \(S\) among all vertices reachable from each vertex. To handle cycles correctly, we extend paths while maintaining the state of each vertex (unvisited, visiting, or resolved).

  • If we extend a path and return to a vertex currently “visiting (state=1)”, a cycle is detected. We find the maximum value \(cm\) of \(S\) among the vertices in the cycle, and set \(\mathrm{maxReach} = cm\) for all vertices in this cycle.
  • For a vertex \(u\) before the cycle (the tree part), we can compute it from back to front as: $\(\mathrm{maxReach}[u] = \max(S_u,\ \mathrm{maxReach}[P_u])\)$
  • If we hit an already “resolved (state=2)” vertex, we similarly propagate the values backward.

Step 2: Precomputing Doubling

  • up[k][v] … the vertex reached after taking \(2^k\) steps from \(v\)
  • mx[k][v] … the maximum value of \(S\) among the \(2^k\) vertices starting from \(v\)

The base cases are: $\(\text{up}[0][v] = P_v,\quad \text{mx}[0][v] = S_v\)\( The transitions are: \)\(\text{up}[k][v] = \text{up}[k-1][\text{up}[k-1][v]]\)\( \)\(\text{mx}[k][v] = \max(\text{mx}[k-1][v],\ \text{mx}[k-1][\text{up}[k-1][v]])\)$

Step 3: Answering Each Quiz

For the quiz of student \(i\) (with difficulty \(d = D_i\)):

  • If maxReach[i] < d, output \(-1\).
  • Otherwise, starting from cur = i, we iterate through \(k\) from the largest to smallest:
    If mx[k][cur] < d (meaning none of these \(2^k\) students can solve it), we jump by setting cur = up[k][cur].

By doing this for all \(k\), cur will stop exactly at the first student where \(S \geq d\). Since maxReach guarantees that a valid answer exists, we will never loop infinitely in a cycle.

Illustration of a Concrete Example

If the path is \(i = a \to b \to c \to \cdots\) and \(S_a, S_b < d \leq S_c\), doubling allows us to skip \(a\) and \(b\) together, stopping at \(c\), which becomes the answer.

Complexity

  • Time Complexity: \(O(N \log N)\) (computing maxReach takes \(O(N)\), while the doubling precomputation and each query take \(O(N \log N)\))
  • Space Complexity: \(O(N \log N)\) (for the doubling table)

Here, \(\log N\) is a constant satisfying \(2^{\text{LOG}} > N\) (in the code, \(\text{LOG} = 18\), since \(2^{18} > 2\times10^5\)).

Implementation Points

  • Converting the input to 0-indexed (e.g., P[i]--) makes it easier to handle (add \(+1\) when outputting).

  • When computing maxReach, using recursive DFS might cause a stack overflow. Therefore, it is better to implement it by iteratively extending the path and managing the state of the vertices (unvisited / visiting / resolved). The key is to process the cycle and the part before it (the tree part) separately.

  • In the doubling search, always verify that maxReach[i] >= d (ensuring an answer exists) before performing the jump process. Failing to do so may prevent escaping the cycle, leading to an incorrect answer.

  • It is faster to format the output as a single string and print it all at once.

    Source Code

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

int main(){
    int N;
    scanf("%d",&N);
    vector<int> P(N), S(N), D(N);
    for(int i=0;i<N;i++){ scanf("%d",&P[i]); P[i]--; }
    for(int i=0;i<N;i++) scanf("%d",&S[i]);
    for(int i=0;i<N;i++) scanf("%d",&D[i]);

    // compute maxReach[v] = max S over all nodes reachable from v (including v)
    vector<int> state(N,0); // 0 unvisited,1 inprogress,2 done
    vector<int> ordIndex(N,-1);
    vector<int> maxReach(N,0);
    vector<int> path;
    path.reserve(N);
    for(int s=0;s<N;s++){
        if(state[s]!=0) continue;
        path.clear();
        int v=s;
        while(state[v]==0){
            state[v]=1;
            ordIndex[v]=(int)path.size();
            path.push_back(v);
            v=P[v];
        }
        if(state[v]==1){
            int idx=ordIndex[v];
            int cm=0;
            for(int k=idx;k<(int)path.size();k++) cm=max(cm,S[path[k]]);
            for(int k=idx;k<(int)path.size();k++){ maxReach[path[k]]=cm; state[path[k]]=2; }
            for(int k=idx-1;k>=0;k--){ int u=path[k]; maxReach[u]=max(S[u], maxReach[P[u]]); state[u]=2; }
        } else {
            for(int k=(int)path.size()-1;k>=0;k--){ int u=path[k]; maxReach[u]=max(S[u], maxReach[P[u]]); state[u]=2; }
        }
    }

    const int LOG=18;
    vector<vector<int>> up(LOG, vector<int>(N));
    vector<vector<int>> mx(LOG, vector<int>(N));
    for(int v=0;v<N;v++){ up[0][v]=P[v]; mx[0][v]=S[v]; }
    for(int k=1;k<LOG;k++){
        for(int v=0;v<N;v++){
            int w=up[k-1][v];
            up[k][v]=up[k-1][w];
            mx[k][v]=max(mx[k-1][v], mx[k-1][w]);
        }
    }

    string out;
    out.reserve(N*7);
    for(int i=0;i<N;i++){
        int d=D[i];
        int ans;
        if(maxReach[i]<d){
            ans=-1;
        } else {
            int cur=i;
            for(int k=LOG-1;k>=0;k--){
                if(mx[k][cur]<d) cur=up[k][cur];
            }
            ans=cur+1;
        }
        out+=to_string(ans);
        out+=(i+1<N?' ':'\n');
    }
    fputs(out.c_str(), stdout);
    return 0;
}

This editorial was generated by claude4.8opus-high.

posted:
last update: