Table of Contents

ExplanationImplementation

Official Editorial

Explanation

Let v[0],v[1],…,v[n−1]v[0],v[1],\dots,v[n-1] denote the input sequence. An interval [i…j][i\dots j] is framed if all three of the following conditions hold:

  • v[i]−i=v[j]−jv[i]-i=v[j]-j
  • v[i]=min⁡(v[i…j])v[i]=\min(v[i\dots j])
  • v[j]=max⁡(v[i…j])v[j]=\max(v[i\dots j])

Our approach will be to iterate over all j=[0,n)j=[0,n) and check whether jj contributes a new empodio with right endpoint jj.

  • Maintain a stack mnmn consisting of all indices ii satisfying the second condition.
  • When we increment jj, repeatedly pop the top element ii of mnmn while v[i]>v[j]v[i]>v[j]. Then add jj to mnmn.
  • To check whether jj is part of an empodio, find the maximum i∈mni\in mn such that v[i]−i=v[j]−jv[i]-i=v[j]-j. If ii is to the right of the rightmost left endpoint of any empodio found so far and v[j]=max⁡(v[i…j])v[j]=\max(v[i\dots j]), then we have found a new empodio.

To check whether v[j]=max⁡(v[i…j])v[j]=\max(v[i\dots j]), we can maintain a separate stack mxmx that stores all indices ii such that v[i]=max⁡(v[i…j])v[i]=\max(v[i\dots j]).

Note: The test data on Yandex has sequences of length greater than 11000001100000 …\dots

Implementation

Time Complexity: O(N)\mathcal{O}(N)

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using db = double;
using str = string; // yay python!
using pi = pair<int, int>;
using pl = pair<ll, ll>;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!