E - 伝言リレー / Message Relay 解説 by admin
claude4.8opus-highOverview
This problem asks us to trace the path of a quiz of difficulty \(D\) passed along a “functional graph” (where each student has exactly one recipient) and find the first student who can solve it (\(S_j \geq D\)). We need to find this quickly for all \(N\) quizzes.
Analysis
Naive Approach
A simple approach is to actually trace the path \(i \to P_i \to P_{P_i} \to \cdots\) for each quiz to find a student with \(S_j \geq D\). However, this takes \(O(N)\) in the worst case per quiz, leading to \(O(N^2)\) overall. This will not run in time (TLE) for \(N = 2 \times 10^5\).
Graph Structure
Each student \(i\) has exactly one recipient \(P_i\). This means the graph is a functional graph (a directed graph where every vertex has an out-degree of 1). Such a graph always consists of:
- At least one cycle, and
- Trees (tails) flowing into the cycles.
If we trace the path of the quiz starting from student \(i\), we will go through the tail, enter a cycle, and eventually return to a previously visited vertex after completing one full loop of the cycle. At that point, the quiz becomes unsolvable (\(-1\)).
Therefore, the number of distinct vertices reachable from \(i\) is:
\[ \text{length} = (\text{distance from } i \text{ to cycle}) + (\text{cycle length}) \]
We only need to inspect these length vertices in order. The first vertex where \(S_j \geq D\) is the answer. If none of these length vertices can solve the quiz, the answer is \(-1\).
Key to Optimization
Linearly searching for “the first vertex on the path where \(S_j \geq D\)” is too slow. Instead, we can use doubling (binary lifting). By precomputing the vertex reached after \(2^k\) steps from each vertex, along with the maximum value of \(S\) in that interval, we can process each query in \(O(\log N)\) time.
Algorithm
Step 1: Identifying vertices on cycles Count the in-degrees of all vertices, and repeatedly remove vertices with an in-degree of 0 (similar to Kahn’s algorithm for topological sort). The vertices that remain and cannot be removed are the ones on the cycles.
Step 2: Calculating dist and comp_len for each vertex
- For vertices on a cycle: dist = 0, and comp_len = cycle length.
- For tail vertices: let dist be the distance to reach the cycle, and comp_len be the length of the cycle they eventually reach.
With this, we can find the number of distinct reachable vertices from each vertex: length = dist + comp_len.
Step 3: Constructing the doubling table
- 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\).
We initialize the tables with up[0] = P and mx[0] = S, and build them using:
\[ up[k][v] = up[k-1][\,up[k-1][v]\,] \]
\[ mx[k][v] = \max(\,mx[k-1][v],\ mx[k-1][\,up[k-1][v]\,]\,) \]
Step 4: Processing each quiz
For each student \(i\) (with quiz difficulty \(D\)), we use binary lifting to greedily skip vertices where \(S < D\), checking from the largest bits down to the smallest.
- If mx[k][cur] < D and making the jump does not exceed length, we can safely jump \(2^k\) steps forward (since no student in this range can solve the quiz).
- If the total steps taken cnt reaches length, it means no reachable student can solve the quiz, so the answer is \(-1\).
- Otherwise, the final position cur is the first student who can solve it.
Complexity
- Time Complexity: \(O(N \log N)\)
- Space Complexity: \(O(N \log N)\)
The doubling table requires \(O(N \log N)\) space, and both the construction and the queries are completed in \(O(N \log N)\) time.
Implementation Details
0-indexed Conversion: The input \(P_i\) is 1-indexed. We subtract
1to convert it to 0-indexed for internal calculations, and add1back for the final output.Meaning of
mx[k][v]: Since we initializemx[0][v] = S[v],mx[k][v]represents the maximum \(S\) among the \(2^k\) vertices starting from \(v\) (inclusive). During queries, we check if the next \(2^k\) vertices to be visited cannot solve the quiz (i.e., their maximum \(S < D\)) before making the jump.Limiting by
length: Since going around a cycle once brings us back to already visited vertices, the total steps jumped in binary lifting must be strictly limited tolength = dist[i] + comp_len[i]. Forgetting this check might cause the search to loop indefinitely around the cycle and return an incorrect student instead of \(-1\).Efficient Tail Distance Calculation: To calculate the distance for tail vertices efficiently, we can traverse from uncalculated vertices, pushing them onto a stack until we reach a cycle (or an already calculated vertex). Then, we backtrack to determine the distances. This ensures each vertex is processed exactly once, keeping the computation efficient.
Source Code
import sys
from collections import deque
def main():
data = sys.stdin.buffer.read().split()
idx = 0
N = int(data[idx]); idx += 1
P = [int(data[idx+i]) - 1 for i in range(N)]; idx += N
S = [int(data[idx+i]) for i in range(N)]; idx += N
Dd = [int(data[idx+i]) for i in range(N)]; idx += N
# Kahn to find non-cycle nodes
deg = [0]*N
for v in P:
deg[v] += 1
q = deque(i for i in range(N) if deg[i] == 0)
removed = [False]*N
while q:
u = q.popleft()
removed[u] = True
v = P[u]
deg[v] -= 1
if deg[v] == 0 and not removed[v]:
q.append(v)
on_cycle = [not removed[i] for i in range(N)]
dist = [-1]*N
comp_len = [0]*N
# find cycles
visited_cycle = [False]*N
for i in range(N):
if on_cycle[i] and not visited_cycle[i]:
nodes = []
v = i
while not visited_cycle[v]:
visited_cycle[v] = True
nodes.append(v)
v = P[v]
L = len(nodes)
for nd in nodes:
comp_len[nd] = L
dist[nd] = 0
# compute dist and comp_len for tail nodes
for i in range(N):
if dist[i] == -1:
stack = []
v = i
while dist[v] == -1:
stack.append(v)
v = P[v]
base_dist = dist[v]
base_len = comp_len[v]
d = base_dist
while stack:
nd = stack.pop()
d += 1
dist[nd] = d
comp_len[nd] = base_len
# binary lifting
LOG = max(1, N.bit_length())
up = [P[:]]
mx = [S[:]]
for k in range(1, LOG):
prevu = up[k-1]
prevm = mx[k-1]
curu = [0]*N
curm = [0]*N
for v in range(N):
m = prevu[v]
curu[v] = prevu[m]
a = prevm[v]; b = prevm[m]
curm[v] = a if a > b else b
up.append(curu)
mx.append(curm)
res = [0]*N
for i in range(N):
D = Dd[i]
length = dist[i] + comp_len[i]
cnt = 0
cur = i
for k in range(LOG-1, -1, -1):
step = 1 << k
if cnt + step <= length and mx[k][cur] < D:
cnt += step
cur = up[k][cur]
if cnt == length:
res[i] = -1
else:
res[i] = cur + 1
sys.stdout.write(' '.join(map(str, res)))
main()
This editorial was generated by claude4.8opus-high.