这个缩进看得我难受,自己对着写了遍,测试样例都没过,楼主看看哪里错了。
typedef long long LL;

int main()
{
    int n;
    cin >> n;
    if (n <= 1)
    {
        cout << 0 << endl;
        return 0;
    }
    vector<LL> a(n);
    for (int i = 0; i < n; i++)
        cin >> a[i];

    stack<pair<LL, int> > s;
    vector<int> c(n), d(n);
    for (int i = 0; i < n; i++)
    {
        while (!s.empty() && s.top().first > a[i])
            s.pop();
        if (s.empty())
            c[i] = -1;
        else
            c[i] = s.top().second;
        s.push(make_pair(a[i], i));
    }
    s = stack<pair<LL, int> >();
    for (int i = n - 1; i >= 0; i--)
    {
        while (!s.empty() && s.top().first >= a[i])
            s.pop();
        if (s.empty())
            d[i] = n;
        else
            d[i] = s.top().second;
        s.push({ a[i], i });
    }
    LL res = 0;
    for (int i = 0; i < n; i++)
    {
        res -= a[i] * (i - c[i]) * (d[i] - i);
    }
    s = stack<pair<LL, int> >();
    for (int i = 0; i < n; i++)
    {
        while (!s.empty() && s.top().first <= a[i])
            s.pop();
        if (s.empty())
            c[i] = -1;
        else
            c[i] = s.top().second;
        s.push({ a[i], i });
    }
    s = stack<pair<LL, int> >();
    for (int i = n - 1; i >= 0; i--)
    {
        while (!s.empty() && s.top().first < a[i])
            s.pop();
        if (s.empty())
            d[i] = n;
        else
            d[i] = s.top().second;
        s.push({ a[i], i });
    }
    for (int i = 0; i < n; i++)
    {
        res += a[i] * (i - c[i]) * (d[i] - 1);
    }
    cout << res << endl;
    return 0;
}