CCCPaste

3119ed6f8eedc

#include <iostream>
#include <vector>
#include <map>
#include <stack>
//#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
int main()
{
ios_base::sync_with_stdio(false);
int n;
cin >> n;

vector<int> v(n);
for(int i = 0; i < n; i++) {
cin >> v[i];
}

vector<int> left(n, -1), right(n, n);

stack<int> st;
for(int i = 0; i < n; i++) {
while(!st.empty() and v[st.top()] > v[i]) {
st.pop();
}
if(!st.empty()) {
left[i] = st.top();
}
st.push(i);
}

stack<int> st2;
for(int i = n - 1; i >= 0; i--) {
while(!st2.empty() and v[st2.top()] > v[i]) {
st2.pop();
}
if(!st2.empty()) {
right[i] = st2.top();
}

st2.push(i);
}

ll total_subarrays = (ll)n * (ll) (n + 1) / 2LL;
total_subarrays %= MOD;

ll bad_subarrays = 0;
for(int i = 0; i < n; i++) {
ll L = i - left[i], R = right[i] - i;

bad_subarrays += (L * R) % MOD;
bad_subarrays %= MOD;
}

cout << (total_subarrays - bad_subarrays + MOD) % MOD << endl;

return 0;
}