E - 伝言リレー / Message Relay Editorial by admin Editorial for printing
gemini-3.5-flash-highOverview
This problem asks us to simulate passing a quiz on a graph where each vertex has an out-degree of exactly 1 (a Functional Graph).
We need to determine whether a quiz starting from each student \(i\) can reach the first student with an academic ability \(S\) of at least the quiz difficulty \(D_i\), before it returns to the same student and loops (resulting in unanswered status).
Analysis
1. Naive Simulation and Its Limitations
For each student \(i\), a naive approach would be to follow \(P_i\) step-by-step until the quiz is solved or caught in a loop. However, in the worst case (e.g., when all students form a single giant cycle), simulating a single quiz would require \(O(N)\) transitions. Since there are \(N\) quizzes, the overall time complexity would be \(O(N^2)\), which will result in a Time Limit Exceeded (TLE) for \(N \le 2 \times 10^5\).
Therefore, we need to speed up the simulation of each quiz.
2. Key to Speedup: “Doubling” and “Maximum Jumpable Steps”
Doubling is a typical technique to speed up transitions. By precomputing the “transition destination after \(2^k\) steps”, we can transition any arbitrary number of steps in \(O(\log N)\) time.
However, this problem has a rule: “If a quiz enters a cycle and visits the same student twice, it becomes unanswered (\(-1\)).” If we use doubling to jump infinitely far ahead, we might overshoot and loop past already visited students.
To prevent this, we need to precompute the “maximum number of students (steps) we can visit starting from student \(i\) without duplication (looping)”. Looking at the structure of the graph, a functional graph consists of “several cycles” and “trees (paths) merging into these cycles”.
- Student \(v\) on a cycle: They can move up to just before returning to themselves after one full loop, so the maximum steps is the “length of the cycle”.
- Student \(u\) on a tree (path): This is the maximum steps of the next student \(P_u\) plus \(1\).
By using this “maximum steps” as an upper bound for doubling, we can search for the “first student with academic ability \(S \ge D_i\)” quickly without getting caught in a loop.
Algorithm
The program operates in the following five steps:
Step 1: Graph Structure Analysis (Topological Sort)
Calculate the in-degree (the number of edges pointing to oneself) of each student, and search by pushing vertices with an in-degree of 0 into a queue in order (topological sort). After this operation, the vertices that still have an in-degree of \(1\) or more are the vertices on the cycles.
Step 2: Calculating Cycle Lengths
For each vertex on a cycle, find the “cycle length” by actually traversing the cycle once. For student \(v\) on a cycle, set the maximum visitable count \(L[v] = (\text{cycle length})\).
Step 3: Calculating Maximum Visitable Counts for Tree Parts
Perform a Breadth-First Search (BFS) starting from the cycle vertices, traversing the edges in reverse. For student \(u\) in the tree part, propagate the maximum visitable count as \(L[u] = L[v] + 1\) using the value of the next student \(v = P_u\). This determines the “maximum steps \(L[i]\) that can be taken without looping” for all students.
Step 4: Constructing the Doubling Tables
Construct the following two tables (where \(K \approx 20\)): - \(next\_node[k][i]\) : The student reached after transitioning \(2^k\) times from student \(i\) - \(max\_S[k][i]\) : The maximum academic ability \(S\) among the \(2^k\) students encountered when starting from student \(i\) and transitioning up to \(2^k - 1\) times
These can be constructed in \(O(N \log N)\) using the following recurrence relations: $\(\text{next\_node}[k+1][i] = \text{next\_node}[k][\text{next\_node}[k][i]]\)\( \)\(\text{max\_S}[k+1][i] = \max(\text{max\_S}[k][i],\ \text{max\_S}[k][\text{next\_node}[k][i]])\)$
Step 5: Answering Queries Using Doubling
Simulate the quiz (difficulty \(D_i\)) distributed to each student \(i\). 1. If \(S_i \ge D_i\), they can solve it themselves, so the answer is \(i\). 2. Otherwise, pass it to the next student \(curr = P_i\), and set the remaining searchable steps to \(rem = L[i] - 1\). 3. For \(k = K-1, \dots, 0\) in descending order, jump ahead using doubling as long as the following conditions are met: - \(2^k \le rem\) (it is within the remaining search range) - \(max\_S[k][curr] < D_i\) (there is no student in this range of \(2^k\) people with enough academic ability to solve the quiz) If the above are satisfied, update \(curr = next\_node[k][curr]\) and subtract \(2^k\) from \(rem\). 4. After the loop ends, if the academic ability of the final \(curr\) is \(S_{curr} \ge D_i\), that student can solve the quiz (the answer is \(curr\)). Otherwise, nobody can solve it, so the result is unanswered (\(-1\)).
Complexity
Time Complexity: \(O(N \log N)\)
- Analyzing the graph (topological sort and BFS) takes \(O(N)\).
- Constructing the doubling tables takes \(O(N \log N)\) (a loop of \(N \times K\) iterations).
- Simulating each quiz takes \(O(\log N)\) time, and since this is done \(N\) times, the overall time complexity is \(O(N \log N)\).
- Overall, it is \(O(N \log N)\), which runs very fast (within about 0.1 seconds) even for \(N = 2 \times 10^5\).
Space Complexity: \(O(N \log N)\)
- It uses \(O(N \log N)\) memory to store the doubling tables \(next\_node\) and \(max\_S\).
- When \(N = 2 \times 10^5\) and \(K = 20\), the number of elements is approximately \(4 \times 10^6\), which takes only tens of megabytes and is well within typical memory limits (such as 1024MB).
Implementation Points
Doubling Initialization and Indexing: Store student \(i\)’s own academic ability \(S[i]\) in \(max\_S[0][i]\) of the doubling table. This allows us to correctly merge the maximum values within the range.
Using Reverse Edges: When calculating the maximum visitable count \(L\) for the tree parts, constructing a reverse adjacency list
rev_adjallows us to smoothly perform BFS starting from the cycles and moving “backwards”.Source Code
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int main() {
// 入出力の高速化
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int N;
if (!(cin >> N)) return 0;
vector<int> P(N + 1);
for (int i = 1; i <= N; ++i) {
cin >> P[i];
}
vector<long long> S(N + 1);
for (int i = 1; i <= N; ++i) {
cin >> S[i];
}
vector<long long> D(N + 1);
for (int i = 1; i <= N; ++i) {
cin >> D[i];
}
// 1. 各頂点の入次数を計算し、逆辺の隣接リストを構築する
vector<int> in_degree(N + 1, 0);
vector<vector<int>> rev_adj(N + 1);
for (int i = 1; i <= N; ++i) {
in_degree[P[i]]++;
rev_adj[P[i]].push_back(i);
}
// 2. トポロジカルソートを用いて、サイクルに含まれない頂点(木の部分)を特定する
queue<int> Q;
for (int i = 1; i <= N; ++i) {
if (in_degree[i] == 0) {
Q.push(i);
}
}
vector<int> temp_in_degree = in_degree;
while (!Q.empty()) {
int u = Q.front();
Q.pop();
int v = P[u];
temp_in_degree[v]--;
if (temp_in_degree[v] == 0) {
Q.push(v);
}
}
// temp_in_degree[i] > 0 の頂点がサイクル上の頂点となる
vector<int> L(N + 1, 0);
vector<bool> visited(N + 1, false);
// サイクル上の頂点について、サイクルの長さを L に設定する
for (int i = 1; i <= N; ++i) {
if (temp_in_degree[i] > 0 && !visited[i]) {
vector<int> cycle;
int curr = i;
while (!visited[curr]) {
visited[curr] = true;
cycle.push_back(curr);
curr = P[curr];
}
int cycle_len = cycle.size();
for (int v : cycle) {
L[v] = cycle_len;
}
}
}
// 3. サイクルから逆向きに BFS を行い、木の部分の頂点の L を計算する
queue<int> bfs_q;
for (int i = 1; i <= N; ++i) {
if (temp_in_degree[i] > 0) {
bfs_q.push(i);
}
}
while (!bfs_q.empty()) {
int v = bfs_q.front();
bfs_q.pop();
for (int u : rev_adj[v]) {
if (temp_in_degree[u] == 0) {
L[u] = L[v] + 1;
bfs_q.push(u);
}
}
}
// 4. ダブリングテーブルの構築
int K = 20;
vector<vector<int>> next_node(K, vector<int>(N + 1));
vector<vector<long long>> max_S(K, vector<long long>(N + 1));
for (int i = 1; i <= N; ++i) {
next_node[0][i] = P[i];
max_S[0][i] = S[i];
}
for (int k = 0; k < K - 1; ++k) {
for (int i = 1; i <= N; ++i) {
next_node[k + 1][i] = next_node[k][next_node[k][i]];
max_S[k + 1][i] = max(max_S[k][i], max_S[k][next_node[k][i]]);
}
}
// 5. 各クイズのシミュレーション(ダブリングによる高速化)
vector<int> ans(N + 1);
for (int i = 1; i <= N; ++i) {
if (S[i] >= D[i]) {
ans[i] = i;
} else {
int curr = P[i];
int rem = L[i] - 1;
for (int k = K - 1; k >= 0; --k) {
if ((1 << k) <= rem) {
if (max_S[k][curr] < D[i]) {
curr = next_node[k][curr];
rem -= (1 << k);
}
}
}
if (rem > 0 && S[curr] >= D[i]) {
ans[i] = curr;
} else {
ans[i] = -1;
}
}
}
// 結果の出力
for (int i = 1; i <= N; ++i) {
cout << ans[i] << (i == N ? "" : " ");
}
cout << "\n";
return 0;
}
This editorial was generated by gemini-3.5-flash-high.
posted:
last update: