Source Code
#include <bits/stdc++.h>
#define F first
#define S second
using namespace std;
typedef long long ll;
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);

	int t;
	cin >> t;
	while (t--)
	{
		ll n;
		cin >> n;

		vector<pair<ll, ll>> a(n + 1);
		vector<ll> pos(n + 1);
		for (ll i = 1; i <= n; i++)
		{
			cin >> a[i].F;
			a[i].S = i;
			pos[a[i].F] = i;
		}

		sort(a.begin() + 1, a.end());

		ll ans = 0, L = 1e9, R = 0;
		for (ll i = 1; i <= n; i++)
		{
			L = min(L, a[i].S);
			R = max(R, a[i].S);

			if (L <= pos[i] && R >= pos[i])
				continue;

			if (pos[i] > R)
			{
				ans += ((pos[i] - R - 1) * i);
				ans += ((L - 1) * i);
				ans += (((pos[i] - R - 1) * (L - 1)) * i);
				ans += i;
			}
			else
			{
				ans += ((n - R) * i);
				ans += ((L - pos[i] - 1) * i);
				ans += (((n - R) * (L - pos[i] - 1)) * i);
				ans += i;
			}
		}

		cout << ans << "\n";
	}

	return 0;
}
Copy
Mex Yamanabdullah1
GNU G++17
79 ms
5.0 MB
Accepted