Source Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<int> idx(n + 1, -1);
        for (int i = 0, x; i < n; ++i) {
            cin >> x;
            idx[x] = i;
        }
        ll ans = 0;
        int mn = idx[0];
        int mx = idx[0];
        ll lst = 0;
        for (int i = 0; i < n && idx[i] != -1; ++i) {
            int pos = idx[i + 1];
            if (pos > mn && pos < mx) {
                continue;
            }
            if (pos < mn) {
                ans += (i + 1) * 1ll * (mn - pos) * (n - mx);
            } else {
                ans += (i + 1) * 1ll * (mn + 1) * (pos - mx);
            }
            lst = ans;
            mn = min(mn, pos);
            mx = max(mx, pos);
        }
        cout << ans << '\n';
    }
    return 0;
}
Copy
Mex Heartbeat
GNU G++17
51 ms
1.1 MB
Accepted