Consider the graph induced by the vertices in an interval .
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 , 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 time and space.
For the full constraints, fix the left endpoint and extend the right endpoint , maintaining connected components with a DSU. Add the new vertex and its edges to neighbors with . 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 . For a fixed , at most union operations succeed and at most one fails. Including vertex iteration and DSU initialization, the total complexity is time and space.
The answer is at most . DSU sizes are at most and the edge count is at most , so every calculation fits in a signed -bit integer.
Solution written by GPT6