Source Code
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define fixed(n) cout << fixed << setprecision(n);
#define mod 1000000007
#define cin(v) for (auto&i:v) cin >> i;
#define cout(v) for (auto&i:v) cout << i << " ";
#define ceil(n,m) (n / m + (n%m != 0))
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()

void lil_codi_vert(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
    #endif
}

//int dx[] = {1, 1, 1, 0, 0, -1, -1, -1};
//int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};



int main(){
    lil_codi_vert();
    ll t; cin >> t;
    while(t--){
        ll n; cin >> n;
        vector<ll> v(n); cin(v);
        int l = 0, r = 0;
        map<ll,ll> ma;
        for(int i = 0; i < n; i++){
            ma[v[i]] = i;
        }
        l = r = ma[0];
        //cout << l << " " << r;
        ll res = n;
        for(int i = 1; i < n; i++){
            if(ma[i] > l && ma[i] < r) continue;
            if(ma[i] > r){
                ll right = ma[i] - r - 1;
                ll left  = l;
                //cout << left << " " << right << "\n"; 
                res += i * (left + right + left * right + 1);
                r = ma[i];
            }else{
                ll left = l - ma[i] - 1;
                ll right = n - r - 1;
                //cout << left << " " << right << "\n";
                res += i * (left + right + left*right + 1);
                l = ma[i]; 
            }
            
        }
        cout << res << "\n";
    }
    return 0;
}
Copy
Mex aboelsoudJr
GNU G++17
372 ms
14.4 MB
Accepted