一道超级经典的单调栈问题,本题的关键在于你不要同时两边取等号,不然相等的区间会重复计算
还有记得开long long
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
const int N = 2e5+10;
int n;
ll a[N];
ll l[N];
ll r[N];
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
a[0] = a[n+1] = -0x3f3f3f3f;
stack<int>stk;
stk.push(0);
for(int i=1;i<=n;i++){
while(stk.size()&&a[i]<=a[stk.top()])
stk.pop();
l[i] = i-stk.top();
stk.push(i);
}
stk = stack<int>();
stk.push(n+1);
for(int i=n;i>=1;i--){
while(stk.size()&&a[i]<a[stk.top()])stk.pop();
r[i] = stk.top()-i;
stk.push(i);
}
ll res = 0;
for(int i=1;i<=n;i++)
res = res + l[i]*r[i]*a[i];
cout<<res<<"\n";
return 0;
}