#include "bits/stdc++.h"
using namespace std;
using i64 = long long;
void solve() {
int n;
cin >> n;
vector<int> pos(n + 1);
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
pos[x] = i;
}
pos[n] = n;
i64 ans = 0;
int l = pos[0];
int r = pos[0];
for (int mex = 1; mex <= n; ++mex) {
l = min(l, pos[mex - 1]);
r = max(r, pos[mex - 1]);
if (pos[mex] < l) {
ans += (i64)mex * (n - r) * (l - pos[mex]);
} else if (pos[mex] > r) {
ans += (i64)mex * (pos[mex] - r) * (l + 1);
} else {
continue;
}
}
cout << ans << '\n';
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
Copy