Source Code
#define _CRT_SECURE_NO_WARNINGS
#include <bits/stdc++.h>
using namespace std;
using std::chrono::high_resolution_clock;
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int, int>pi;
typedef pair<ll, ll>pl;
typedef vector<pi>vpi;
typedef vector<pl>vpl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<string> vs;
const double PI = acos(-1);
const ll oo = 1e18 + 7;
const int MOD = 1e9 + 7;
const int N = 1e6 + 1;
#define endl '\n'
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()
#define read(v) for (auto& it : v) scanf("%d", &it);
#define readL(v) for (auto& it : v) scanf("%lld", &it);
#define print(v) for (auto it : v) printf("%d ", it); puts("");
#define printL(v) for (auto it : v) printf("%lld ", it); puts("");
auto Time() {
	return high_resolution_clock::now();
}
void solve() {
	int n;
	scanf("%d", &n);
	vi v(n);
	read(v);
	vvi idx(1e5 + 5);
	for (int i = 0; i < n; i++)
		idx[v[i]].push_back(i);
	ll ans = 0;
	map<pi, bool>vis;
	for (int i = 0; i < n; i++) {
		for (int j = 1; j * j <= v[i]; j++) {
			if (v[i] % j == 0 && !vis[{v[i], j}] && !vis[{j, v[i]}]) {
				int cur = j;
				int id = lower_bound(all(idx[v[i]]), idx[cur].back()) - idx[v[i]].begin();
				if (id >= idx[v[i]].size())
					continue;
				vis[{v[i], cur}] = vis[{cur, v[i]}] = true;
				cur = idx[cur].back();
				if (cur != idx[v[i]][id])
					ans += ((cur + 1) * (n - idx[v[i]][id]));
				cur = v[i] / j;
				if (cur != j) {
					int id = lower_bound(all(idx[v[i]]), idx[cur].back()) - idx[v[i]].begin();
					if (id >= idx[v[i]].size())
						continue;
					vis[{v[i], cur}] = vis[{cur, v[i]}] = true;
					cur = idx[cur].back();
					if (cur != idx[v[i]][id])
						ans += ((cur + 1) * (n - idx[v[i]][id]));
				}
			}
		}
	}
	printf("%lld\n", ans);
}
int t = 1;
int main() {
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
#endif
	scanf("%d", &t);
	while (t--) solve();
}
Copy
Powerful Inversions Malik
GNU G++17
3070 ms
5.0 MB
Time Limit Exceeded