#include <bits/stdc++.h>
#define ld long double
#define ll long long
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define sz(s) (int)(s.size())
const ll N = 2e5+3, mod = 1000000007;
const ll OO = 6e18;
const auto EPS = 1e-6;
const auto PI = acos(-1);
using namespace std;
int DX[] = { 1, -1, 0, 0, -1, 1, 1, -1 };
int DY[] = { 0, 0, 1, -1, 1, -1, 1, -1 };
int dx[] = { 1,0,-1,0 } ,dy[] = { 0,1,0,-1 };
void testCase()
{
int n;
cin >> n;
map<ll, ll>mp;
for(int i=1;i<=n;i++)
{
int x; cin >> x;
mp[x] = i;
}
ll res = 0, mn = mp[0], mx = mp[0];
for(int i=1;i<=n;i++)
{
if(mp[i]<mn)
{
ll left = mn-mp[i]-1, right = n-mx;
res += i*(left+right+(left*right)+1);
}
else if(mp[i]>mx)
{
ll left = mn-1, right = mp[i]-mx-1;
res += i*(left+right+(left*right)+1);
}
mn = min(mn, mp[i]);
mx = max(mx, mp[i]);
}
cout << res << '\n';
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t = 1; cin >> t;
for(int tc = 1;tc<=t;tc++)
{
//cout << "Case #" << tc << ": ";
testCase();
}
return 0;
}
Copy