Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code

#include <bits/stdc++.h>
using namespace std;

long long solve(vector<long long> &a) {
    int n = a.size();

    stack<int> st;
    vector<int> nse(n), pse(n);
    for (int i = 0; i < n; i++) {
        while (!st.empty() && a[st.top()] > a[i]) {
            nse[st.top()] = i;
            st.pop();
        }
        if (st.empty()) {
            pse[i] = -1;
        } else {
            pse[i] = st.top();
        }
        st.push(i);
    }
    while (!st.empty()) {
        nse[st.top()] = n;
        st.pop();
    }

    long long ans = 0;
    for (int i = 0; i < n; i++) {
        ans += a[i] * (i - pse[i]) * (nse[i] - i);
    }

    return ans;
}

int main() {
    int n;
    cin >> n;
    vector<long long> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    cout << solve(a) << endl;
}
#include <bits/stdc++.h>
using namespace std;

long long solve(vector<long long> &a) {
    int n = a.size();
    set<pair<int, int>> store;
    for (int i = 0; i < n; i++) {
        store.insert({a[i], i});
    }

    set<int> alive;
    vector<int> nse(n), pse(n);

    // Process elements from small to large.
    // By the time a[i] is inserted, all smaller elements would be alive.
    for (auto ele : store) {
        int idx = ele.second;
        auto itr = alive.upper_bound(idx);
        if (itr != alive.end()) {
            nse[idx] = *itr;
        } else {
            nse[idx] = n;
        }

        if (itr != alive.begin()) {
            itr--;
            pse[idx] = *itr;
        } else {
            pse[idx] = -1;
        }

        alive.insert(idx);
    }

    long long ans = 0;
    for (int i = 0; i < n; i++) {
        ans += a[i] * (i - pse[i]) * (nse[i] - i);
    }

    return ans;
}

int main() {
    int n;
    cin >> n;
    vector<long long> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    cout << solve(a) << endl;
}