Reachability An interval is awesome exactly when, for each , every integer in occurs among . The requirement is empty when . For sufficiency, finish the elements from left to right. Each increment from to uses a finished earlier element equal to . For necessity, an increment at position from to needs an earlier element equal to . If that element ends above , its own increment past needs an even earlier element equal to . Indices strictly decrease, so this chain must end at an element whose final value is . A final value below is impossible because values never decrease.
Allowed starting positions Let be the largest with , or if absent. For , define
Set when . Then is awesome exactly when for all . Compress the distinct values of in sorted order. If the number of distinct values in is less than , set . Otherwise all required integers exist in the compressed domain, and a range-minimum segment tree of last occurrences computes . Initialize occurrences to , query before updating the occurrence of to , and never enumerate a potentially huge value interval.
Allowed ending positions For each , find the first with . Set , or if there is no such position. The awesome intervals starting at have precisely the ends . If , none exist. A segment tree over finds the first violating position by descending into nodes whose minimum is below , in per start.
Offline counting Let count awesome intervals with and ; it is zero if either argument is negative. Each query equals
Put . Only valid starts with contribute, each by . Let and be their count and sum of indices, obtained from prefix sums. Process all prefix queries in increasing . Insert valid starts with into two Fenwick trees indexed by , storing their count and sum of . Let the prefix results through be and . Then
The correction is zero at ; the reference uses strict inequality for insertion.
Subtasks and complexity For subtask 1, enumerate intervals and simulate increments while finishing elements left to right. Reject immediately if an increment count exceeds the number of earlier elements. This takes time and space, including a two-dimensional prefix table for queries. For subtask 2, fix and extend . Maintain the earlier final values as disjoint consecutive integer runs in an ordered map. Check whether one run contains in , then insert and merge neighboring runs. Build a two-dimensional prefix table of valid intervals. Time is and space is . The full solution takes time and space. Answers are at most . Use signed 64-bit integers for counts, prefix sums, products, and inclusion-exclusion.
Solution written by GPT6