We are asked: given n points (ri, ci) on an n x n grid, with all ri distinct and all ci distinct. So it's a permutation: we have a permutation p where row i has a monster at column p(i)? Wait, input: n lines each with ri, ci. All ri distinct, all ci distinct. So essentially we have a set of n points, one per row and one per column. So we can treat this as a permutation: for each row r, there is a unique column c (the column of the monster in that row). Since rows are distinct and columns are distinct, it's a bijection.
We need to count the number of k x k square subgrids (contiguous square of size k, meaning rows [i, i+k-1] and columns [j, j+k-1] for some i, j) that contain exactly k monsters. Since there are exactly n monsters total, and each row and column has exactly one monster. For a square subgrid of size k, it contains some number of monsters (the points whose row is in the row range and column is in the column range). We need exactly k.
This is a classic problem: counting submatrices in a permutation matrix that are squares and contain exactly one per row and column within the square? Wait, condition: exactly k monsters in a k x k square. Since there is exactly one monster per row overall, but within the square rows, there could be between 0 and k monsters (since each of those rows has a monster somewhere, but its column might be outside the column range). Similarly, columns distinct, so the set of monsters in the square is exactly the set of rows i in row range such that the column of that monster lies in column range. So it's like we have permutation p: row i -> column p(i). We consider intervals of rows [l, r] of length k, and intervals of columns [a, b] of length k. We need that the number of rows i in [l, r] with p(i) in [a, b] equals k. That means every row in [l, r] has its column in [a, b], and also since columns are distinct, automatically the set of columns from these rows will be exactly k distinct columns within [a, b]; but if they are all in [a, b], then there are exactly k distinct columns, so they must exactly be the columns in [a, b] (since there are only k columns in that range, and we have k rows each with distinct columns). So condition is equivalent to: the set of column values for rows in [l, r] is exactly the interval [a, b]. That is, the permutation restricted to the rows interval has column values that form a contiguous interval of length k. So the problem reduces to: In a permutation of size n, count the number of intervals (contiguous segments) of rows such that the values (columns) of those rows form a contiguous interval. Because given such an interval of rows [l, r] with length k, the columns values set is exactly some interval [min, max] of length k, which would correspond to a k x k square (rows [l, r] and columns [min, max]). Conversely, any k x k square that contains exactly k monsters must have rows interval [l, r] and columns interval [a, b] such that the set of columns for rows [l, r] is exactly [a, b], so the rows interval is "good". And also note that for a given rows interval [l, r] that is good, the columns interval is uniquely determined as [min(p(l..r)), max(p(l..r))]. So each good rows interval corresponds to exactly one square. Also, could there be squares that are not aligned such that rows interval is contiguous and columns interval is contiguous? Yes, squares are defined by contiguous rows and columns intervals of equal length. So indeed the mapping is bijective: each square with exactly k monsters corresponds to a contiguous rows interval of length k whose column values form a contiguous interval of length k. So answer = number of intervals [l, r] (1 ≤ l ≤ r ≤ n) such that max(p[l..r]) - min(p[l..r]) = r - l.
That's a classic problem: count number of intervals in a permutation where max - min = length. There's known O(n) or O(n log n) solutions using stacks and segment trees, or divide and conquer. Since n up to 3e5, we need O(n log n) or O(n). Let's think.
We need to count intervals where max - min = length. This is similar to counting intervals where the set of numbers in the interval is a permutation of a contiguous range. There are many known solutions. One approach: For each right endpoint r, count how many l such that condition holds. Use segment tree to maintain for each possible left index the value of (max - min - (r - l)). At each step r, we update structures to reflect new max and min when extending to r. Then we need to count how many left indices have this expression = 0. However, maintaining this directly with segment tree and lazy propagation could be O(n log n). Alternatively, we can use two monotonic stacks for max and min, and maintain a segment tree that tracks max - min + l (or something). Let's derive.
Define for a fixed r, and for each l ≤ r, let M(l, r) = max_{i=l..r} p(i), m(l, r) = min_{i=l..r} p(i). Condition: M(l, r) - m(l, r) = r - l. This is equivalent to M(l, r) - m(l, r) + l = r. So for each r, we need number of l such that f(l) = M(l, r) - m(l, r) + l equals r.
Now as we increase r, we can maintain for each l the current value of M(l, r) and m(l, r) (they are non-decreasing in r for fixed l? Actually, as r increases, M(l, r) is non-decreasing, m(l, r) non-increasing). We can maintain these values with segment tree with range updates: when we add a new element p(r), it will affect intervals whose max or min change. Classic approach: maintain two monotonic stacks: one for max (decreasing) and one for min (increasing). For each step r, we update the stacks and assign new max to a segment of l's, similarly new min. With lazy propagation we can update the segment tree to adjust the values of M(l, r) and m(l, r) for ranges of l. Also we need to add + l to the expression. So we can maintain a segment tree where each leaf l stores value = M(l, r) - m(l, r) + l. Initially (r=0), no elements, but we can think of before processing we set M and m as undefined. When we start, for each r we consider only l <= r, so for l > r we ignore. Typically, we maintain for all l from 1 to n, but only those l <= r are active? We can handle by updating only when r grows: for each new r, we set for l = r: M(r,r)=p(r), m(r,r)=p(r), so value = p(r)-p(r)+r = r. But we need to maintain for all l < r as well. So segment tree over indices 1..n, we maintain value f(l) for each l. At step r, we update max/min for some segments of l (those whose max is updated to p(r) or min updated to p(r)). Then we need to count number of l in [1, r] such that f(l) = r. Since f(l) depends on r, we can query the segment tree for count of leaves with value exactly r.
However, we need to ensure that for l > r, those values are not considered. But they may be outdated; we can either set them to something that never equals r, or just query only range [1, r]. But we need to know that for l > r, we haven't updated them appropriately (they'd correspond to intervals that haven't started). Typically, we can initialize f(l) to something like INF, or we can maintain that we only update for l <= r? But it's easier to maintain for all l, but when we update max/min, we only update segments that correspond to l in [1, something]? Actually, the max/min updates affect all l <= current r, because when we consider a new r, for any l <= r, the interval [l, r] includes the new element, so max/min may change. So the updates should apply to all l in [1, r]. But the stack method determines the ranges of l where the new element becomes the new max (or min). Those ranges are within [1, r]. So we can apply updates to exactly those ranges. For l > r, intervals [l, r] with l > r are invalid; we don't care. So we can just not update them. But our segment tree covers all indices 1..n. For l > r, we want to ensure they don't get counted. We can simply query only in [1, r]. So we need to be able to query count of indices in [1, r] with value exactly r.
Now we need to maintain f(l) = M(l, r) - m(l, r) + l. As r increases, we increment r? Actually, r is fixed at each step. For each r, we need to know f(l) based on current max and min of interval [l, r]. When we add a new element, we need to update f(l) for all l from 1 to r: add something to adjust for changes in M and m. Also, note that the term +l is constant per leaf, doesn't change with r. So we can maintain two values per leaf: max and min (or just the diff). But it's easier to maintain f(l) = A(l) + l, where A(l) = M(l, r) - m(l, r). So we can maintain A(l) via segment tree with range add updates when max/min change. Because when the new element is larger than previous max for some intervals, then M(l, r) increases by delta; that adds delta to A(l). Similarly, if new element is smaller than previous min, then m(l, r) decreases, so A(l) increases by -delta (since minus min increases). So we can update A(l) by adding the change in M and change in (-m). More concretely, we can maintain two separate values: current max and min. But using stacks we can compute for each r, the effect on max: we maintain a stack of indices with decreasing values (max stack). For the new index r, we pop while stack top value < p(r). For each popped segment, the previous max was the value at the top, but now p(r) becomes the new max for those l that had that max as the current max. Actually the typical method: For each r, we maintain an array of max contributions: for each l, the current max over [l, r] can be thought of as the maximum of p over indices from l to r. As r increases, the max for a given l might change only when we encounter a new element greater than all previous in [l, r]. The intervals of l where the max changes are determined by the max stack. Specifically, let max_stack contain indices i1 < i2 < ... such that p(i1) > p(i2) > ...? Actually for max we maintain decreasing values: we want to know for each segment of left endpoints, which element provides the max. As we move right, we maintain a stack where values are strictly decreasing? Typically for "range maximum query" evolution, we can use a monotonic decreasing stack: when we see a new element, we pop while stack top value <= new value (or < depending). Then the intervals of l where the current max equals the value of some stack element can be determined. There's a known technique to maintain f(l) = max - min + l with range add updates using two monotonic stacks. I recall a classic problem "Number of subarrays where max - min <= k" uses two deques and incremental counting. But here we need exact equality, which might be easier because we can track the min and max separately and count zeros.
Alternatively, we can solve by divide and conquer: For each interval, we can count good subarrays by considering the mid and expanding. But that would be O(n log n) with careful handling. Since n is up to 3e5, O(n log n) is fine. However, typical divide-and-conquer for counting intervals with max-min = length might be O(n log n) but each recursion we need to compute contributions crossing mid. That can be done by scanning left and right with maintaining min and max. But careful: For each left side we can compute for each left index the min and max as we extend to the right, and similarly from right to left. Then we need to count pairs (l, r) crossing mid such that max(l,r)-min(l,r)=r-l. This can be done by considering cases where the max is on left or right, etc. But there is known solution: number of intervals in permutation with consecutive values property. I've seen solution using segment tree and stacks. Let's examine both.
Option 1: Segment tree with lazy propagation for range add and query count of a specific value. However we also need to support query of count of a specific value r. Since r increases each step, we need to know how many indices have f(l) = r. This is like a "value frequency" query. We can maintain segment tree that for each node stores the minimum value and the number of times it appears (or also second minimum?) Wait, we need to count exact value r, not just minimum. But we know that f(l) = M - m + l. Could it be that f(l) is always >= r? Let's check: For any interval [l, r], we have M - m >= (some), but is M - m + l always >= r? Actually, by properties: M - m >= (max - min) obviously, but can we say M - m + l >= r? Consider trivial: l = r, then M=m=p(r), so M-m+l = l = r, equality. For larger intervals, M - m is at least the difference between distinct numbers; is it always >= r-l? Not necessarily; e.g., permutation [2,1] for l=1,r=2: M=2,m=1 => M-m=1, l=1 => M-m+l=2, r=2, equality. But sometimes it could be > r. For example, permutation [1,3,2]: interval l=1,r=3: M=3,m=1 => M-m=2, +l=3 => 5, r=3 => > r. So f(l) can be > r. Actually, condition is equality when the numbers form a consecutive set. Otherwise f(l) > r, because M - m >= (r - l) (since in a set of r-l+1 distinct integers, the max-min is at least (r-l) (since min + (r-l) <= max if they are consecutive? Actually, if you have k distinct integers, the difference between max and min is at least k-1. So for size k, M - m >= k-1 = (r-l). So M - m + l >= r. So f(l) >= r always, with equality iff the numbers form a consecutive set. So at each step r, f(l) is at least r. Actually check: For interval length k = r-l+1, we have M - m >= k-1, so M-m+l >= k-1+l = (r-l) + l = r. So indeed f(l) >= r, with equality iff M - m = r-l. So we are counting indices l where f(l) = r. Since f(l) is always at least r, we can maintain the segment tree and query for the number of indices that have the minimum value (since min overall could be r) and check if the minimum equals r, then count min occurrences. But careful: f(l) for different l may be > r; we need exactly those with f(l)=r. Since f(l) >= r, the smallest possible value among all l in [1,r] is exactly r? Not necessarily; the minimum over l could be > r if no good interval ending at r. But we know at least l=r gives f(r)=r, because for l=r, M=m=p(r), so M-m+l = r. So leaf l=r always has f(l)=r. Therefore, the minimum value among all l in [1,r] is always exactly r, because leaf r is exactly r, and all others are >= r. So at step r, the minimum value in the segment tree over range [1,r] is exactly r, and the count of indices achieving that minimum is the number of l such that f(l)=r (since any index with f(l)=r achieves the minimum, and because minimum is r, any index with f(l)=r is a min). So we can maintain a segment tree that stores the minimum value in each node and the count of that minimum. Then we can apply range add operations (since we will be adding deltas to f(l) for ranges when max or min updates). At each step r, after updating, we query the node for range [1,r] to get the minimum and its count. Since we know the minimum is r, we can just take the count (but we should verify that indeed no index can have f(l) < r; we argued it's always >= r, and leaf r gives exactly r, so min = r). So answer += count.
Thus we need a data structure that supports:
- range add: add a value to all elements in a range.
- query over a range: get the minimum value and the number of occurrences of that minimum.
Initially, before processing any elements, we need to set up the values for l from 1 to n. However, we will process r from 1 to n incrementally. At step r, we consider intervals ending at r. For each l, we maintain f(l) = M(l, r) - m(l, r) + l. At the start (r=0), there are no elements; but we can initialize all f(l) to something? Actually, when r=0, no intervals. We'll build as we go. At step r, we want to have correct f(l) for all l ≤ r. The standard incremental method: Start with an empty array f(l) for l=1..n, but we will only ensure those l <= r are correct after processing r. At r=1, we need to set f(1) = M(1,1)-m(1,1)+1 = 1. But before processing r=1, we could set all f(l) to something like 0? But then after updates we'll get correct. A common approach: Initialize f(l) = l for all l? But M(l,r)-m(l,r) not yet defined. Actually, before any elements, M and m are not defined. So we build as we go: when we process r=1, we need to initialize f(1) appropriately. But we can also think of initially setting f(l) = 0 (or some base) and then as we add elements, we add contributions from max and min. But note that for l=r, f(l) = l because M=m=p(r). So we need to ensure that after processing r, leaf r has value r. That will happen if we start with f(l) initially = l? Because for l=r, when r is first considered, we need to have M=m=p(r) so M-m =0, so f(l)=l. So if we start with f(l)=l for all l, then as we extend r, we need to add (M - m) contributions. But initially, for l < r, M and m for the interval [l,r] are not just p(r) but include earlier elements. So we need to update f(l) for l<r by adding the increase in M and decrease in m relative to the previous state when r-1 was the end. So we can maintain f(l) as: f(l) = l + (current max over [l, r] - current min over [l, r]). Actually, M - m is the extra part. At r=0 (no elements), for any l, there is no interval. So we can't define that. But we can start with r=1: For l=1, we want f(1)=1+0=1. For l>1, we don't care yet. So we can initialize an array A of size n, set A[l] = l initially? Then as we process r from 1 to n, we will apply range adds that adjust for M and min. However, note that for l>r, the formula f(l) = l + M(l,r)-m(l,r) is not defined because the interval [l,r] with l>r is invalid. But we might still maintain it; but we will only query up to r. To avoid incorrect updates for l>r, we should ensure that when we apply range adds for max/min changes, we only apply to l in [1, r]? Actually, the updates are derived from the effect of adding a new element at r. For any l ≤ r, the interval [l, r] includes this new element, so M and min may change. For l > r, the interval [l, r] is invalid (empty). So we should not consider them. However, if we maintain the segment tree for all indices 1..n, we need to ensure that for l > r, we don't update them, because those intervals shouldn't exist. The stacks method for updates identifies ranges of l where the max/min changes; these ranges are always within [1, something]. Typically, the stack method works by maintaining for each element its "influence" region: For the max stack, when we pop, we compute the range of left endpoints for which the popped element was the max before, and now the new element becomes the max. That range is typically from (previous stack index +1) to the popped index (or something). However, this range is always within [1, r]. So if we apply the range add to exactly that segment, we won't affect l > r because the range is within 1..r. Also, we need to initialize the segment tree with base values. But what about l that are not yet "active"? For l > r, we will never update them until we reach that r. But we might query [1, r] and we need correct values for l <= r. For l>r, we don't care. So we can set initial values for all l as something. However, we also need to consider that for l <= r, before processing any element, we need a starting point. The easiest: start with f(l) = l for all l. Then when r=1, we will apply updates to reflect M and min? But for l=1, we want M(1,1)=p(1), m(1,1)=p(1) so M-m=0, so f(1) should be 1. If we start with f(1)=1, and we apply no update for max/min for l=1 because when we process r=1, we need to set that the new element is both max and min for intervals that include it. But using the stack approach, we will push r onto both stacks and update ranges where the new element becomes new max or new min. For max, when we add p(1), the stack was empty, so we might add a range update for l from 1 to 1 (or maybe 1 to 1) to add the difference between new max and old max. But old max for interval [1,0] is undefined. To handle smoothly, we can think that before processing any element, for all l, we have M = -inf? Actually, an easier approach: At step r, we first add the contribution of the new element as follows: We consider that initially for all l ≤ r, the current f(l) is based on intervals ending at r-1. When we extend to r, we need to incorporate p(r) into M and m. We can treat it as: for all l ≤ r, we need to add (increase in M) and subtract (decrease in m). The increase in M for a given l is max(0, p(r) - old_M(l,r-1)). Similarly, decrease in m is max(0, old_m(l,r-1) - p(r)). So we need to add these deltas to f(l). Using stacks, we can compute ranges where p(r) is greater than the current max. Those ranges' old max is some value less than p(r), and after update, the new max becomes p(r). So the delta added is p(r) - old_max. For ranges where the old max is already >= p(r), delta = 0. Similarly for min.
Thus we need to be able to add a value (p(r) - old_max) to a contiguous range of l. This is done by storing for each l its current max? But we don't store that directly; we use the stack to know the previous max values. In the stack approach, we maintain a stack of pairs (index, value) representing the current maximum for ranges of left endpoints. When we encounter a new element at r with value v, we pop from the stack while the top's value < v. For each popped segment, we identify the range of left endpoints for which that popped element was the current maximum. Then we add to that range the difference (v - popped_value) to f(l). After popping, we push the new element with its influence range. We also need to know the current min stack similarly, but with signs.
Alternatively, we can maintain two segment trees that store the current max and min, but that would be heavy. So the stack + range add is standard.
Implementation plan:
-
Use a segment tree that supports range add (lazy propagation) and can query over a range [1, r] the minimum value and count of minimum. Since we only need the count of minimum, and we know the minimum is r (we can verify), but to be safe we just query min and count and add count to answer.
-
We'll maintain f(l) = l + cur_max_contrib(l) - cur_min_contrib(l)? Actually we need to define precisely what we store in the segment tree. Let's define arr[l] = (current M(l, current_r) - current m(l, current_r) + l). Initially, before processing any r, we can set arr[l] = 0? But then when r becomes active, we need to add contributions. Let's think of incremental building: we will iterate r from 1 to n. At each step, we want to update arr[l] for all l from 1 to r to reflect inclusion of p(r). Also we need to initialize arr[r] appropriately when r first becomes the right endpoint? Actually, at step r, after updates, we want arr[l] for each l in [1, r] to be correct for intervals ending at r. For l = r, M(r,r)=p(r), m(r,r)=p(r), so arr[r] should be r. But if we start with arr[l] = l for all l, then at step r, after updating with previous elements (r-1), arr[r] would have been l? Wait, initially set arr[l] = l? That would mean for l, we consider that initially M(l,0)-m(l,0) = 0? That's not correct because for intervals with empty set, max/min are undefined. But we can think of building incrementally: before processing any elements, we have r=0. Then we start r=1: we need to update arr[l] for l=1..1 (since only l=1) to incorporate p(1). If we start arr[1] = 1, we can proceed: but we also need to consider that before processing, arr[1] = 1, but we haven't added M-m. For interval [1,1], M-m=0, so arr[1] should be 1. That's fine. But we also need to consider that for l=1, the stack updates will add something? Let's simulate: When we process r=1, we will update max and min. For max, we push index 1 with value p(1). The stack was empty. Typically, we would pop nothing, then we add a range update for the segment of l where this new element becomes the new max. Which segment? For a max stack, the influence region of an element at index i is from previous stack element's index +1 to i (or 1 to i if stack empty). More precisely, the standard algorithm for maintaining "max over range [l, r]" as r increases: we maintain a stack of indices where values are decreasing. For each index i, we can define the "previous greater" element to the left (strictly greater? Since we want to know for which left endpoints the element i is the maximum). Actually, for a fixed right endpoint r, the maximum for left endpoint l is the maximum of p[l..r]. This can be represented by the "next greater to the right" or something. When we move r, we update.
Simplify: Let's adopt the approach used in many solutions for counting subarrays with max-min = length: Use segment tree storing value = max - min + l. Maintain two stacks: one for max, one for min. At each step r, we update the stacks and perform range adds to adjust for changes in max and min. Then query the number of indices in [1,r] where value = r (or min = r). Since we have arr[l] = l initially, and then we add (max contribution) and subtract (min contribution). But careful: Initially, before any updates, arr[l] = l, but that would correspond to assuming M(l,0)-m(l,0)=0, which is not defined but works because when we add the first element, we will add the increase in max and decrease in min from some baseline? Let's think: At r=0, there is no element. When we go to r=1, we need to set M(l,1) and m(l,1) for l=1 only. For l=1, M= m= p(1). If we start with arr[1] = 1, we then need to add the delta for max: delta_max = p(1) - old_max. But old_max for interval [1,0] is not defined. Usually, we treat old_max as -inf, but that would add huge value. So we cannot start with arr[l]=l and then add deltas from undefined state.
Better approach: Instead of initializing arr[l] = l, we can initialize arr[l] = 0 (or some other) and then later add l. Actually, we need to include the +l term. So we could maintain base = l separately, maybe store it as constant per leaf. So segment tree leaf initially could be set to l. Then as we process elements, we add updates for max and min contributions. But then for intervals that haven't been "activated" yet (l > r), we don't want to update them. But we will not update them because updates only apply to ranges within [1, something] that are <= current r. So leaf l will get updates only when r >= l. That's fine. But we need to ensure that for l=r, after we have processed up to r, the value becomes l + (M - m) = l + 0 = l. Since we start with arr[l] = l, and we will apply updates for max and min when processing r. For l = r, at the moment we process r, we will apply updates for max and min that affect left endpoints in some range that includes l=r? Let's examine: When we process new element at index r, we will push onto max stack. The algorithm for updating max typically: while stack not empty and value[stack.top] < p(r) (for max stack), we pop. For each popped, we have a segment where that popped element was the current max; we need to add to that segment the difference (p(r) - popped.value) to arr. Then after popping, we push the new element and define its influence segment. But for the new element itself, it becomes the max for some segment of left endpoints, specifically from (previous stack top index + 1) to r (if stack empty, from 1 to r). However, for the new element, we also need to add its contribution? Actually, before adding the new element, for left endpoints in that segment, the current max was the value of the previous stack top (or -inf if none). But we need to add the difference between new max and old max to arr. So when we push the new element, we should apply a range add to its influence segment of (p(r) - old_max), where old_max is the previous max in that segment (the value of the element that was previously the max for that segment, or -inf if none). But after popping, we have already updated the popped segments with the increase to the new max. Then for the new element's own segment, the old max might be something else? Actually, consider the segment of left endpoints for which the new element becomes the new max after processing. The max stack after popping contains elements with values > p(r) (if we maintain decreasing stack, we pop while top.value < p(r) to maintain strictly decreasing? Actually, for max we want to know for each left endpoint the maximum is the maximum among values from that index to r. The typical monotonic stack for max is decreasing: we pop while top.value <= p(r) (or <). Usually for "max" we maintain a stack where values are decreasing, and when we see a new value, we pop all values less than it because they will never be the max for any future left endpoints? Let's derive properly.
We need to maintain, for each left index l, the current maximum over [l, r] as r moves. For a fixed r, the function max(l) = max_{i in [l, r]} p(i) is a non-increasing function as l increases (since removing elements can only decrease max). As r increases, for each l, max(l) can only increase when the new element p(r) is greater than the previous max for that l.
We can maintain a stack of pairs (start_index, value) representing that for left endpoints in [start_index, next.start_index-1], the current max is value. This is a piecewise constant function. When we add a new element at r, we compare its value with the values in the stack. Since max is decreasing as l increases, the stack should have values in decreasing order. The top of stack corresponds to the segment of smallest l (starting at 1) with the largest max. When we add a new element with value v, we need to update the function: For all l such that the current max(l) < v, we set max(l) = v. Since max(l) is decreasing in l, the set of l where max(l) < v is a suffix of the current domain? Actually, because max(l) decreases as l increases, the values start high near l=1 and eventually drop. So if v is large, it might affect the beginning part. More precisely, we can maintain a stack where each entry corresponds to a segment where max is constant. The entries are in order of increasing l? Typically we store from left to right: first entry covers leftmost segment with highest max, then next with lower max, etc. When we encounter a new value v, we pop entries from the stack while the value of the entry is < v, because those segments will now have max updated to v. After popping, the new segment for v will start at the leftmost index of the last popped segment (or 1 if stack empty). Then we push a new entry with start = that leftmost index, value = v. Additionally, we need to record the effect on f(l): For each popped segment, we need to add to arr[l] for l in that segment the difference (v - old_value) because the max increased by that amount. After popping all segments with value < v, we push the new segment but we do not immediately add any delta for that segment? Actually, for the new segment we push, the max for those l becomes v, but we have already added the delta for the popped segments. However, what about the segment where the old max was >= v? Those segments remain unchanged. So the algorithm: For max stack (maintaining segments of constant max), we store for each segment its start index (the leftmost l where this max applies) and its value. The stack is ordered by start index increasing (so top is the segment with highest start? Actually easier: maintain stack where each element is (start, value) and the stack is monotonic decreasing in value? Let's define as:
We keep a stack max_stk that holds segments in order of increasing start index (i.e., from leftmost to rightmost). The first element in stack (bottom) corresponds to l=1. But to make updates easy, we often use a stack of indices (positions) where the values are monotonic. Another typical method: we maintain a stack of indices where p[index] is decreasing. For each index i, we can compute the previous greater element (PGE) to the left. The influence region where i is the maximum for left endpoints is (prev_greater_index, i] (i.e., left endpoints strictly greater than prev greater index). Then when we move r from i-1 to i, we need to update the max for left endpoints in (prev_greater_index, i] because now p(i) is the new maximum for those l? Actually, careful: For a fixed right endpoint r, the maximum for left endpoint l is max_{k in [l, r]} p(k). This maximum is the maximum of all elements from l to r. As r increases, the new element p(r) becomes the new maximum for those l such that p(r) > max_{k in [l, r-1]}. That is, for l where the current max (before adding p(r)) is less than p(r). The set of such l is a contiguous prefix? Since max(l) is non-increasing in l, the condition max(l) < p(r) holds for l from some point L to r (maybe?). Actually, max(l) decreases as l increases, so if for some l0, max(l0) < p(r), then for all l >= l0, max(l) <= max(l0) < p(r) because max(l) is non-increasing. Also for l < l0, max(l) >= p(r). So the set of l with max(l) < p(r) is a suffix: [L, r] for some L. So we need to add delta = p(r) - old_max to those l in [L, r]. The point L is the first index where old_max >= p(r). To find L efficiently, we can maintain a stack of previous indices with decreasing max values. The stack holds indices where p[index] is decreasing. For each new index r, we pop from stack while stack not empty and p[stack.top] < p(r). Each popped index corresponds to a segment where that index was responsible for the max for some range of left endpoints. Actually, we can think of the max function being represented by a partition of [1, r] into segments, each assigned to the rightmost occurrence of the maximum? Hmm.
Standard approach for this type of problem (counting subarrays where max-min = length) is to maintain two monotonic stacks and a segment tree that stores value = max - min + index. At each step, we update the segment tree with range adds for changes in max and min. This is described in many solutions for "Good Subarrays" (where condition is max-min = length). Actually, there is a known problem: "Number of subarrays with max-min = length" (or "Beautiful subarrays") which can be solved in O(n). Usually, they maintain a segment tree with min and count of min. They use stacks to update contributions.
Let's search memory: Codeforces problem "Pudding Monsters" is equivalent to counting intervals in permutation where max-min = length. I recall an editorial solution: compress coordinates, use divide and conquer with segment tree, or use stack + segment tree. I think the classic solution uses divide and conquer: For each segment, count intervals that cross the middle, by scanning left and right while maintaining min and max, and using the condition max-min = length. There is a known O(n log n) divide-and-conquer solution. Because n up to 3e5, O(n log n) is acceptable. But we need to be careful with time and memory. I'll examine both.
Divide and Conquer approach: For an array a (permutation) of size n. Count intervals [l, r] such that max(l..r) - min(l..r) = r - l. We can solve with recursion: function solve(l, r) for segment. If l==r: count 1 (single element always satisfies). Else, let mid = (l+r)//2. Count intervals entirely in left (solve(l,mid)), entirely in right (solve(mid+1,r)), and crossing intervals that include mid. For crossing intervals, we need to count pairs (i,j) with i <= mid < j such that condition holds. We can compute from mid outward.
We can compute arrays for left side: for i from mid down to l, compute minL[i] = min(a[i..mid]), maxL[i] = max(a[i..mid]), and length = mid - i + 1. Similarly for right side: for j from mid+1 to r, compute minR[j], maxR[j] for range [mid+1, j].
Now for crossing intervals, we consider two cases: either the maximum of the whole interval is on the left side or on the right side, similarly for minimum. But we can handle by considering all possible intervals. One approach: For each left index i, we can consider possible right indices j and check condition using precomputed values. But naive O(n^2). However, we can use the property that as we move away from mid, the min and max change monotonically.
Standard solution for counting intervals where max-min = length uses the following trick for crossing intervals: For each possible left i, we can find candidate j such that condition holds using two pointers, but due to two dimensions it's more complex. Actually, there is known O(n) method for crossing intervals using four cases: max on left and min on left; max on left and min on right; max on right and min on left; max on right and min on right. But the condition max-min = (j-i+1). For crossing intervals, we can fix where the maximum and minimum are located: either both on same side, or one on left one on right. But we can handle by enumerating j and use data structures.
Another approach: Use the fact that the condition is equivalent to: (max - min) - (j - i) = 0. For crossing intervals, we can compute contributions from the left and right sides separately using prefix arrays of min and max and using two pointers.
I recall a known solution for the problem "CF 319C" or something? Wait, there is Codeforces problem 319C? Actually, "Pudding Monsters" is Codeforces Round #... I think it's Codeforces 526F / 645F? Wait, CF 526F is "Pudding Monsters" but the simplified version? Actually, Codeforces 526F is "Pudding Monsters". And there is also "Pudding Monsters" is CF 526F? Yes, I recall that Codeforces 526F (or maybe 529B) but I'm pretty sure 526F is "Pudding Monsters". The problem statement matches. So the editorial for CF 526F discusses both a divide-and-conquer O(n log n) solution and a stack + segment tree O(n) solution. Many participants used divide-and-conquer. Let's recall that editorial.
The classic solution for 526F: Since the permutation has distinct numbers, condition max-min = len is equivalent to that the numbers in the interval form a contiguous segment. The solution uses divide and conquer: For each segment, we count intervals that cross the middle. We compute from the middle the min and max on both sides. Then we consider four cases, but it's known that we can handle by scanning and using two pointers. Let's reconstruct.
We have left part indices i from mid down to l, right part j from mid+1 to r. For each i, we can compute min_i = min(a[i..mid]), max_i = max(a[i..mid]). For each j, min_j = min(a[mid+1..j]), max_j = max(a[mid+1..j]). For a crossing interval [i, j], overall min = min(min_i, min_j), overall max = max(max_i, max_j). The condition is max - min = j - i.
We can consider two scenarios:
- The overall max and min are both on the same side (both on left or both on right).
- The max is on one side and min on the other.
We can count each separately.
Case 1: Both max and min on left. That means max_i > max_j and min_i < min_j? Actually, both on left means the overall max is max_i (i.e., max_i >= max_j) and overall min is min_i (i.e., min_i <= min_j). Then condition becomes max_i - min_i = j - i. So for a fixed i, j must satisfy j = i + (max_i - min_i). Also we need to ensure that j is on the right side (j >= mid+1) and that the condition about max and min being on left holds: max_i >= max_j and min_i <= min_j. So we can iterate i from mid down to l, compute needed j = i + (max_i - min_i). If j is within right part and also satisfies the dominance conditions, we count it. But checking dominance condition for each i may be heavy if we need to check max_j and min_j for that specific j. However, we can precompute data structures for right side to answer queries: For a given needed j, we need to know whether max_j <= max_i and min_j >= min_i. That's like a 2D condition. Could be done with segment tree offline. But the editorial might have a more clever approach: Because as we move i, the needed j changes; but perhaps we can handle case 1 and case 2 together with a two-pointer sweep that maintains something.
Alternatively, there is a known O(n) method for crossing intervals using the idea that for each possible value of (max - min) we can adjust. I recall a solution using two pointers for each side and counting intervals where max-min = length by considering relative positions of min and max. Actually, I've solved similar problems (like counting subarrays where max-min <= k) using two deques, but equality is trickier.
Let's search memory: There is a well-known solution for CF 526F using a segment tree and stacks. That solution is O(n log n) but also can be O(n) with a modified segment tree that tracks min and count. I think the stack+segment tree solution is more straightforward to implement if we are comfortable with lazy segment tree.
Given that n <= 3e5, O(n log n) is fine. So we can implement the segment tree + stacks approach.
Thus I'll adopt the segment tree + stacks.
Key steps:
- Let arr be of size n+1 (1-indexed). We'll build a segment tree over indices 1..n, where each leaf l initially stores value = l (since at r=0, there are no elements, but we'll later add contributions from max and min. However, as argued, at step r, after all updates for including element r, we want f(l) = M(l,r) - m(l,r) + l. To achieve this, we start with arr[l] = l, and then for each r, before query, we update the tree to add the increases in max and decreases in min that result from adding p(r). But careful: At the very first step r=1, before any updates, arr[1] = 1. But we need to incorporate the max and min from p(1). For l=1, M-m=0, so arr[1] should stay 1. That's fine if we do nothing. However, if we follow the stack update procedure, we will push p(1) onto stacks and we might apply a range add to segment where it becomes new max/min. But for l=1, the old max was -inf? We need to ensure we don't add extra.
To avoid this, we can treat that initially, before any elements, for all l, we set arr[l] = l and also maintain that the current max for all l is -inf and min = +inf? But then adding first element would require huge updates. Instead, we can start with r=0, and then for each r from 1 to n, we first set up something for the new element at position r as a base. A common trick: At step r, before processing updates, we set arr[r] = r (or we can set it manually) and then treat that for l = r, the max and min are p(r). But we need to also update the stacks so that they know about the new element. The stack algorithm normally works by considering that before processing r, we have current max and min for intervals ending at r-1. Then we add p(r) and update.
To incorporate p(r) correctly, we need to start with some initial state for r=0: max stack empty, min stack empty. Then for r=1:
- For max: The stack is empty, meaning that for all l in [1, r-1] (none) there is no max? But for l=1..1, we need to set max to p(1). So we should treat that the new element becomes the max for l in [1,1] (since only l=1). In the stack algorithm, when stack is empty, we will push r onto max stack, and we should apply a range add to [1, r] of (p(r) - (-inf))? But that would be huge. Instead, we can treat the initial "old max" for the range [1,1] as something like p(1) itself? Actually, we can avoid range adds for the new element's own segment by noticing that for l=r, the old max and min for interval [l, r-1] doesn't exist, so we should set the base properly.
Simplify: We can initialize arr[l] = l for all l. Then we set up the stacks such that they contain some sentinel values representing that for indices beyond current r, the max/min are undefined. But when we push a new element, we should only update ranges where the old max was less than p(r). For the segment that includes l = r, the old max for [r, r-1] is undefined; we want the new max to be p(r) and we don't want to add any delta because arr[r] currently is r (since we set it to l = r). But if we try to add delta (p(r) - old), we would add a huge delta. So we must ensure that for l = r, we don't apply an extra delta. Therefore, we should initialize the stacks such that for each r, before processing, we treat that for the new index r, we set arr[r] = r, and also we push the element onto the stacks, but we should not perform any range add for the segment that includes r because its old max was undefined.
One way: Instead of starting with arr[l] = l, we can start with arr[l] = 0, and then at each step r, before any updates, we set the leaf r to value r (or we can do an assignment). But we have range adds that affect multiple indices. Alternatively, we can maintain f(l) = M(l,r) - m(l,r) + l, and we can update incrementally by:
- When we extend r, for all l <= r-1, we need to add delta_max and delta_min. For l = r, we need to initialize f(r) = r (since M = m = p(r)). So we can do: at step r, first set leaf r to r (by doing a point assign? but we have range adds that affect it later? Actually, we will later apply range adds that affect intervals including l=r. But if we set leaf r to r, and then later we apply range adds that affect l=r (like if p(r) becomes new max/min for l=r? but l=r is the only index where interval is just [r,r]; obviously p(r) is both max and min, so delta_max and delta_min for l=r would be zero because old max/min for [r, r-1] is undefined. So we must ensure we do not apply any delta for l=r. So we need to exclude l=r from the range updates for max and min. The stack updates typically affect ranges of left endpoints l where the new element becomes the new max/min. For l=r, does the new element become new max? For interval [r, r], the max is p(r). In the stack representation, the segment where the new element becomes the new max is from (previous stack top index + 1) to r. If the stack is empty, that segment is [1, r]. That would include l=r. But in reality, for l=r, the old max was undefined; we should not add delta. However, if we start with arr[r] initialized to r, and then we add a range add of (p(r) - old_max) to [1, r] where old_max is something like -inf, that would add a huge amount, messing up. So we need to adjust: We should treat that for l=r, the old max is p(r) (so delta=0) because there was no previous element. How to achieve that? Perhaps we can treat that before processing r, we have already set the max and min for l up to r-1, and for l = r, we haven't set anything yet. We can handle separately: when we add new element r, we first set leaf r to r (or set some initial value). Then we update stacks, but we restrict the range updates to l in [1, r-1] only. This way, l=r is unaffected by the delta updates. Then after updating, we push the new element onto stacks with its influence range starting at (previous top index +1) but we should adjust the range to exclude r? Actually, when pushing, we need to define the segment of l for which this new element is the current max. That segment should include l = r? For intervals starting at r, the max is p(r). So the new element is indeed the max for l in some range that includes r. But if we excluded l=r from the range add, we need to ensure that the final value for l=r after all operations is correct. Since we set leaf r to r initially, and we do not add any delta, it's already correct because M-m=0. And after pushing, the stack's representation of max for l=r will be p(r). But we don't need to store the max values; we only use stacks to compute range adds for future updates when a larger element appears. For that, we need to know for which l this element is the current max. So for l=r, it is indeed the current max. So when later a larger element appears, we will pop this element and update the segment including l=r with the delta. That is fine because at that time, for l=r, the old max is p(r) and we will add delta = new_value - p(r). That will correctly update f(l) for l=r. So we just need to avoid adding an initial delta for the new element's own segment when it is first added. So we can do: when processing a new r:
- Set leaf r to r (point update to value r). However, note that our segment tree supports range adds and point assign? We could do a point set to r, but if we have lazy propagation, we can also do a point assignment by reading current value and adding difference. But it's easier: we can maintain that initially we set all leaves to their index l (by building the segment tree with initial values l). Then before processing any r, we have arr[l]=l for all l. But at step r, for l = r, that leaf currently has value = r (since it was built). That is correct base. However, we will later apply range adds for max and min that affect l = r. For the first element, we will push it onto stacks. But for the first element, when we push, we will pop nothing, and then we would normally add a range add to segment [1, r] of (p(r) - old_max). If we treat old_max for the segment as something like -inf (since stack empty), we would incorrectly add to l=r. So we need to modify the algorithm to not perform that initial range add. Instead, we can initialize the stacks with a dummy element at index 0 with value -inf for max stack and +inf for min stack, such that the range for a new element is from (prev_index+1) to r, and for the dummy, prev_index = 0. Then we can compute the delta as (new_value - old_value) where old_value is the value of the previous stack top (which for max stack could be -inf). But if we use -inf, then delta is infinite. So we need to avoid that. Instead, we can treat that for the new element's segment, we should only add delta for the part where the old max is defined, i.e., for l from prev_index+1 to r-1? Actually, for l = r, there was no previous max, so we shouldn't add anything. So we can split: the range where the new element becomes the new max is [prev_index+1, r]. But for l = r, the old max is undefined. However, if we consider that before adding the new element, the max for l = r was not defined because the interval [r, r-1] is empty. But we want f(l) after adding to be l + (M - m). Since initially, for l=r, we have value l (from initialization). And we want after all updates, it remains l because M-m=0. So we should not add any delta for l=r. So we should only add delta to [prev_index+1, r-1]. But what about l in [prev_index+1, r-1]? Those l correspond to intervals that previously ended at r-1 and had some max. So we need to add delta to them. So we can, when pushing a new element, after popping, we compute the range of l that were covered by the popped elements (which excludes r), and add deltas. Then for the new element's own segment, we push with start = something, but we do not add a delta for its own segment now. Later, when this element gets popped by a larger element, we will add delta to its entire segment (including l=r) at that time. That will be correct because at that time, for l=r, the old max is p(r) (since that element was the max), and we will add delta = new_value - p(r), which will adjust f(l) accordingly. So the algorithm:
Initialize segment tree with arr[l] = l for all l.
Initialize max_stk = empty, min_stk = empty.
For r from 1 to n:
// Update max contributions
while max_stk not empty and p[max_stk.top] < p[r]:
pop top. Let idx = top.index, val = p[idx].
// The segment where this idx was the current max is from (next top index + 1) to idx? Actually we need to know the range of left endpoints for which this idx was the max.
// In stack representation, we typically store for each element the leftmost l for which it is the max. When we pop, we know the next element below (or start) gives the boundary.
// So we need to store in stack not only indices but also the left boundary of its segment (the l range for which this element is the current max).
// Commonly, we store pairs (index, left_boundary) or just index and compute left boundary as previous stack top's index + 1.
// Let's define: For max_stk, we maintain a stack of indices where p is decreasing. For each index i in the stack, the segment of left endpoints l for which i is the rightmost maximum (i.e., the maximum over [l, current_r] is p[i]) is from (previous index in stack + 1) to i (or from 1 to i if none). But as we push new indices, the segment for each index may shrink because later larger elements override it for some l. However, when we maintain the stack while processing sequentially, we can keep track of the "boundary" for each element: the leftmost l for which it is currently the maximum. A standard method: We keep a stack where each element is (index, left_boundary). For max, we initialize left_boundary = index when pushing. When we pop, we adjust the left_boundary of the new top? Actually, an easier method: We can maintain a stack of indices only, and also an auxiliary array of "prev" boundaries. But let's think in terms of range updates.
There's a known pattern:
For max updates:
// maintain stack of indices with decreasing p values.
// Also maintain a variable 'last' for the left boundary of the new element.
last = r;
while max_stk not empty and p[max_stk.top] < p[r]:
idx = max_stk.pop();
// For the segment where idx was the max, the left boundary is from (stack empty ? 1 : max_stk.top+1) to last? Actually need to recall.
// When we pop idx, the segment for which idx was the max is from (previous index in stack + 1) to idx? But since we are at current r, the max for left endpoints might have been overridden earlier? Let's reconstruct.
Better to adopt a known implementation: Many solutions for counting good subarrays use two stacks and segment tree. I'll try to recall exact implementation from known code.
I recall a typical solution:
int n;
int a[N]; // permutation 1-indexed
SegmentTree st; // supports range add, and query of min and count of min in [1, r]
long long ans = 0;
stack<pair<int, int>> smax, smin; // each store (value, position) maybe with left boundary?
But more common: They maintain two stacks that store (value, index) and also the effect on the segment tree via range add.
Alternative: I can use a simpler approach: maintain two arrays for current max and min contributions using a Fenwick tree? But range adds needed.
Let's design from scratch:
We maintain f(l) = l + A(l) - B(l), where A(l) is current max over [l, r], B(l) is current min over [l, r]? Actually f(l) = max(l,r) - min(l,r) + l.
Let cur_max[l] be the current max for intervals ending at current r, for each l. But we don't store directly; we use stacks to know piecewise constant segments.
As r increases, cur_max[l] can only increase when p(r) > previous max. The set of l where cur_max[l] changes is a contiguous segment from some L to r (maybe). Actually, cur_max[l] is non-increasing as l increases. So when p(r) arrives, it will become the new max for l from some L to r, where L is the smallest index such that cur_max[l] < p(r). Since cur_max[l] is non-increasing, there is a threshold L: for l < L, cur_max[l] >= p(r); for l >= L, cur_max[l] < p(r). So we need to add (p(r) - cur_max[l]) to f(l) for l in [L, r]. But we don't know L directly. We can find it using the max stack. The stack maintains the boundaries where cur_max changes. Specifically, we can maintain a stack of pairs (index, value) such that for left endpoints in (prev_index, index] the current max is value. Actually, typical representation: Let the stack store indices i1 < i2 < ... < ik = r (not necessarily r, but the indices where cur_max changes). The leftmost segment is [1, i1] with max = p(i1); next segment is (i1, i2] with max = p(i2); ... ; last segment is (i_{k-1}, r] with max = p(r). The values p(i) are decreasing along the stack (since if a later index had a larger value, it would have overridden earlier segments). So we can push r onto stack after popping indices with smaller values. When we pop an index i, we are removing its segment. That segment's left boundary is from (previous stack top's index + 1) to i (if stack empty after pop, left boundary from 1 to i). For that segment, we need to add delta = p(r) - p(i) to f(l) for l in that left boundary range, because those l will now have new max p(r) instead of p(i). After popping all indices with smaller values, we push r onto stack. But what about the segment for r itself? The segment for r will be from (new stack's previous top index + 1) to r. We do NOT add any delta for that segment now because for those l, the max was previously something (maybe from the element that remains after popping) and is already >= p(r)? Wait, after popping all smaller elements, the stack top (if any) has value >= p(r). For l in (prev_top_index, r], the current max before adding r was the max of the segment that was previously covered by the popped elements? Actually, before adding r, for l in (prev_top_index, some popped indices] the max was the value of the popped element (which was less than p(r)). After popping, those l become part of the new segment where the new max is p(r). But what about l in (last popped index? Let's step through.
Suppose before processing r, the max stack contains indices i1, i2, ..., ik (in increasing order, with decreasing values). These indices represent that for l in (i_{t-1}, i_t] (with i0 = 0), the current max is p(i_t). The rightmost segment is (i_{k-1}, i_k] with max = p(i_k). Note that i_k is the last index where a max change occurred, and i_k <= r-1. Now we add new element r with value v = p(r). We pop from the stack while the value at stack top < v. For each popped index i_t, we remove its segment. That segment's left boundary is from (prev index in stack after popping? Actually, if we pop i_t, the next element below it (if any) is i_{t-1}. For l in (i_{t-1}, i_t], the max was p(i_t). After popping, those l will get a new max (which will eventually be v, because v is larger). So we need to add delta = v - p(i_t) to f(l) for l in that segment. After we finish popping, the new stack's top (if any) has value >= v. For l in (new top's index, r], the max will become v. But what was the max for those l before? For l in (new top's index, i_last_popped? Actually after popping, the remaining stack contains indices with values >= v. The leftmost l not covered by any of the popped segments? Let's define L as the index after the top of stack (after popping). Specifically, after popping, let prev = stack.top (if stack not empty) else 0. Then the range (prev, r] is now covered by the new element r, because for any l in (prev, r], the maximum of [l, r] is v? But careful: For l in (prev, some earlier index], the max might be determined by the element at prev if its value is > v? Actually, if the stack after popping has top index i with value >=