Source Code
#include <iostream>
#include <iomanip>
#include <queue>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <bitset>
#include <set>
#include <cstdio>
#include <string>
#include <stack>
#include <map>
#include <sstream>

#define ll long long
#define sz(s) (int)s.size()
#define all(x) x.begin(), x.end()
using namespace std;
void AIA()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
}
void file()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
}
const int OO = 1e9 + 7;
const long double PI = acos(-1);
int dx[] = {0, 0, 1, -1, 1, -1, 1, -1}, dx4[] = {0, 1, 0, -1};
int dy[] = {1, -1, 0, 0, 1, -1, -1, 1}, dy4[] = {1, 0, -1, 0};
int main()
{
    // Verify Your thought before Coding.
    AIA();
    file();
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        vector<ll> ind(n + 1);
        for (int i = 1; i <= n; i++)
        {
            int a;
            cin >> a;
            ind[a] = i;
        }
        ll L = ind[0], R = ind[0], res = n;
        for (int i = 1; i < n; i++)
        {
            //   cout << L << " " << R << " " << ind[i] << "\n";
            if (ind[i] < L)
                res += (n - R + 1) * (L - ind[i]) * i;
            else if (ind[i] > R)
                res += (ind[i] - R) * L * i;
            L = min(L, ind[i]);
            R = max(R, ind[i]);
        }
        cout << res << "\n";
    }
}
Copy
Mex kareemabdelrhmane
GNU G++17
52 ms
1.9 MB
Accepted