Source Code
#include <bits/stdc++.h>

using namespace std;

int main() {
    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;
        }
        long long ans = 0;
        int mn = idx[0];
        int mx = idx[0];
        long long 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<<endl;
    }
	return 0;
}
Copy
Mex Mohamedmaher
GNU G++17
88 ms
1.9 MB
Accepted