Source Code
#include <iostream>
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
	std::ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);
	int t;
	cin >> t;
	while (t--) {
		int n; cin >> n;
		vector<ll>a(n), v(n);
		for (int i = 0; i < n; i++) {
			cin >> a[i];
		   v[a[i]]= i;
		}
		//for (int i = 0; i < pos.size(); i++)cout << pos[i] << ' '; cout << "\n";
		ll ans = n, mn = INT_MAX, mx = INT_MIN;
		for (int i = 0; i < n - 1; i++) {
			mn = min(mn, v[i]);
			mx = max(mx, v[i]);
			int x = 0, y = n - 1;
			if (v[i + 1] > v[i]) y = v[i + 1] - 1;
			else x = v[i + 1] + 1;

			if (mn<x || mx>y)continue;
			ans += (y - mx + 1) * (mn - x + 1) * (i + 1);
		}
		cout << ans << "\n";
	}
	return 0;
}

Copy
Mex Walaa Abd Elhady
GNU G++17
51 ms
3.4 MB
Accepted