Source Code
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
#include <unordered_map>
//#include"testlib.h"
#define endl '\n'
#define all(v) v.begin(),v.end()
#define allr(s) s.rbegin(),s.rend()
#define RT(s) return cout<<s,0
#define sz(s)    (int)(s.size())
//#define PI acos(-1)
#define EPS 1e-8
#define watch(x) cout << (#x)<<" = "<<x<<endl
#define mk(x, y) make_pair(x, y)
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
int dy[] = { 1, -1, 0, 0, -1, 1, 1, -1 };
int dx[] = { 0, 0, 1, -1, 1, -1, 1, -1 };
void file() {
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
	//freopen("C:\\Users\\karemo\\source\\repos\\generator\\generator\\out.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
#else
	//freopen("gcd.in", "r", stdin);
	//freopen("out.txt", "w", stdout);
#endif
}


void fast() {
	std::ios_base::sync_with_stdio(0);
	cin.tie(NULL);
}

int main() {
	file();
	fast();
	int t; cin >> t;
	while (t--) {
		int n; cin >> n;
		vi v1(n), fre(n);
		vii arr(n);
		for (int i = 0; i < n; i++) {
			cin >> v1[i];
			fre[v1[i]] = i;
			arr[v1[i]] = { i, i };
		}
		for (int i = 1; i < n; i++)
			arr[i].first = min(arr[i].first, arr[i - 1].first),
			arr[i].second = max(arr[i].second, arr[i - 1].second);
		ll ans = 0;
		for (int i = 0; i < n; i++) {
			int L = arr[v1[i]].first, R = arr[v1[i]].second;
			if (v1[i] == n - 1) {
				ans += (L + 1) * 1LL * (n - R) * (v1[i] + 1);
				continue;
			}
			int num = fre[v1[i] + 1];
			if (num >= L && num <= R)
				continue;
			if (num <= L)
				ans += (L - num) * 1LL * (n - R) * (v1[i] + 1);
			else
				ans += (L + 1) * 1LL * (num - R) * (v1[i] + 1);
			//cout << ans << endl;
		}
		cout << ans << endl;
	}
	return 0;
}
Copy
Mex karemo
GNU G++17
60 ms
3.5 MB
Accepted