DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

✧ ✦ Spark of Exam Luck ✦ ✧

Back to problem

Editorial

Consider the graph induced by the vertices in an interval [L,R][L,R][L,R].

The graph must be connected for every student to receive a spark. If a connected graph contains a cycle, a spark can reach that cycle and keep traveling around it forever. Conversely, in a tree, sparks follow the unique paths from the starting vertex. The last delivery happens no later than time R−L≤N−1R-L \le N-1R−L≤N−1, so the time condition is satisfied. Thus, we need to count intervals whose induced graphs are trees.

For small inputs, inspect every interval directly. Run BFS to check connectivity and check that the number of internal edges is one less than the number of vertices. This takes O(N2(N+M))O(N^2(N+M))O(N2(N+M)) time and O(N+M)O(N+M)O(N+M) space.

For the full constraints, fix the left endpoint LLL and extend the right endpoint RRR, maintaining connected components with a DSU. Add the new vertex RRR and its edges to neighbors uuu with L≤u<RL \le u < RL≤u<. An edge within one component creates a cycle. That cycle remains when increases, so stop processing this . Whenever there is no cycle and exactly one component remains, add to the answer. Do not stop merely because the graph is disconnected: a later vertex may join its components.

For each vertex, store only its smaller-numbered neighbors in decreasing order. Stop iterating as soon as a neighbor is smaller than LLL. For a fixed LLL, at most N−LN-LN−L union operations succeed and at most one fails. Including vertex iteration and DSU initialization, the total complexity is O(Mlog⁡N+N2α(N))O(M\log N + N^2\alpha(N))O(Mlog time and space.

The answer is at most N(N+1)/2=50 005 000N(N+1)/2=50\,005\,000N(N+1)/2=50005000. DSU sizes are at most 10 00010\,00010000 and the edge count is at most 1 000 0001\,000\,0001000000, so every calculation fits in a signed -bit integer.

Solution written by GPT6

R
RRR
LLL
111
N
+
N2α(N))
O(N+M)O(N+M)O(N+M)
646464