#include //#include //#pragma GCC optimize("Ofast") using namespace std; #define reps(i,s,n) for(int i = s; i < n; i++) #define rep(i,n) reps(i,0,n) #define Rreps(i,n,e) for(int i = n - 1; i >= e; --i) #define Rrep(i,n) Rreps(i,n,0) #define ALL(a) a.begin(), a.end() using ll = long long; using vec = vector; using mat = vector; ll N,M,H,W,Q,K,A,B; string S; using P = pair; const ll INF = (1LL<<60); template bool chmin(T &a, const T b){ if(a > b) {a = b; return true;} else return false; } template bool chmax(T &a, const T b){ if(a < b) {a = b; return true;} else return false; } template void my_printv(std::vector v,bool endline = true){ if(!v.empty()){ for(std::size_t i{}; i class BIT { //T has operator "+=" and can be initialized with 0. unsigned int n; vector bitree; public: BIT(unsigned long _n) : bitree(_n + 1, 0) { n = _n; } void add(int id, T x) { ++id; while (id <= n) { bitree[id] += x; id += id & -id; } } T sum(int id) { ++id; T temp(0); while (id > 0) { temp += bitree[id]; id -= id & -id; } return temp; } }; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); cin>>N; vec a(N + 2); vector

low, high; reps(i, 1, N + 1) cin>>a[i]; a[0] = (a[1] > a[2] ? 0 : N + 1); a[N+1] = (a[N-1] < a[N] ? 0 : N + 1); reps(i, 1, N + 1){ if(a[i] < a[i+1]) low.emplace_back(a[i], min(a[i-1], a[i+1])); else high.emplace_back(a[i], max(a[i-1], a[i+1])); } ll res = 0; sort(ALL(low)); { BIT bit(N + 10); for (P p : low) { res += bit.sum(N + 5) - bit.sum(p.first); bit.add(p.second, 1); } } sort(ALL(high)); reverse(ALL(high)); { BIT bit(N + 10); for(P p : high){ res += bit.sum(p.first); bit.add(p.second, 1); } } reverse(ALL(high)); BIT bit(N + 10); for(P &p : low) { swap(p.first, p.second); bit.add(p.second, 1); } sort(ALL(low)); int lsz = low.size(), hsz = high.size(); int i{}, j{}; const P inf(INF, INF); while(i < lsz || j < hsz){ P p = inf, q = inf; if(i < lsz) p = low[i]; if(j < hsz) q = high[j]; if(p.first < q.first){ bit.add(p.second, -1); ++i; }else{ //cout<