Source Code
//#include <bits/stdc++.h>
#include <iostream>
#include <bitset>
#include <map>
#include <vector>
#include <set>
#include <queue>
#define ll long long
using namespace std;
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		ll n;
		ll cnt=0;
		cin >> n;
		vector<ll> v(n), idx(n, 0);
		for (auto &it : v)
			cin >> it;
		for (int i = 0; i < n; i++)
			idx[v[i]] = i;
		ll mn = idx[0], mx = idx[0];
		for (int i = 1; i < n; i++)
		{
			if (idx[i] > mx)
			{
				cnt+=((mn+1)*(idx[i]-mx))*i;
			}
			else if (idx[i] < mn)
			{
				
				cnt+=((n-mx)*(mn-idx[i]))*i;
			}
			mn = min(mn, idx[i]);
			mx = max(mx, idx[i]);
		}
		cnt+=n;
		cout<<cnt<<endl;
	}
}
Copy
Mex Amrharb
GNU G++17
91 ms
3.5 MB
Accepted