

思路:
往右看能看到山顶,可以看成找第一个比当前元素>=的元素,即构造单调递减栈。
例子:
7 5 3 4
1. 7入栈: 7
2. 5入栈: 7 5 ans=ans+1(1是指有1个元素(7)可以看到5)
3. 3入栈: 7 5 3 ans=ans+2(2是指有2个元素(7,5)可以看到3)
4. 3出栈4入栈: 7 5 4 ans=ans+2(2是指有2个元素(7,5)可以看到4)
所以最终ans=1+2+2=5
易错点:
开long long。
判断元素是否进栈需要判断 s.top() <= num,不要忘记等号。
使用 ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);在C++中关闭输入输出流的同步,以提高程序的执行效率。
或者使用scanf和printf,避免超时
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e6 + 10;
ll n;
stack<ll> s; // 单调栈
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    ll ans = 0;
    ll num;
    for (ll i = 1; i <= n; i++)
    {
        cin >> num;
        while (!s.empty() && s.top() <= num) // 栈顶<=要进来的元素:栈顶元素出栈
        {
            s.pop();
        }
        s.push(num);
        ans += s.size() - 1;
    }
    cout << ans;
    return 0;
} 
或者使用scanf和printf
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e6 + 10;
ll n;
stack<ll> s; // 单调栈
int main()
{
    scanf("%d", &n);
    ll ans = 0;
    ll num;
    for (ll i = 1; i <= n; i++)
    {
        scanf("%d", &num);
        while (!s.empty() && s.top() <= num) // 栈顶<=要进来的元素:栈顶元素出栈
        {
            s.pop();
        }
        s.push(num);
        ans += s.size() - 1;
    }
    printf("%d", ans);
    return 0;
}
                


















