给出n个数,问其中有多少三元组(a, b, c)使得 [(a, b) = (b, c) = (a, c) = 1] or [(a, b) ≠ 1 and (a, c) ≠ 1 and (b, c) ≠ 1]。
n <= 10^5, ai <= 10^5.
首先可以把问题抽象为有n个点,两两连边,有红边和蓝边,问三边同色三角形有多少。
然后考虑算反面,发现只要找从一个点出发的两种边分别有几条并相乘,加起来除二即可。
所以只用算与ai互质的有几个。发现ai <= 10^5。这样只需变为数组b,记录一个元素出现几次,再用容斥做即可。
容斥:枚举x,num[x] = sigma(x | d, b[d]), c[d] += -mu[x] * num[x]。c数组为与它不互质个数。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#define Rep(i, x, y) for (int i = x; i <= y; i ++)
#define RepE(i, x) for (int i = pos[x]; i; i = g[i].nex)
using namespace std;
typedef long long LL;
const int L = 100000, N = L + 5;
int n, a[N], u[N], pri[N], pz, T;
bool c[N];
LL ans, tot, b[N];
void Pre() {
u[1] = 1;
Rep(i, 2, L) {
if (!c[i]) pri[++ pz] = i, u[i] = -1;
Rep(j, 1, pz) {
int k = i * pri[j];
if (k > L) break ;
c[k] = 1, u[k] = -u[i];
if (i % pri[j] == 0) { u[k] = 0; break ; }
}
}
}
int main()
{
Pre();
cin >> T;
while (T --) {
scanf ("%d", &n);
memset (a, 0, sizeof(a));
memset (b, 0, sizeof(b));
ans = tot = 0;
int x;
Rep(i, 1, n) scanf ("%d", &x), a[x] ++;
Rep(i, 2, L) {
int num = 0;
for (int j = i; j <= L; j += i) num += a[j];
for (int j = i; j <= L; j += i) b[j] += -u[i] * num;
}
ans = LL(n) * (n-1) * (n-2) / 6;
Rep(i, 2, L) b[i] -= a[i];
// Rep(i, 1, 10) cout << a[i]<<" "<<b[i]<<endl;
Rep(i, 1, L) x = n - a[i] - b[i], tot += ((b[i]*a[i]) + (a[i]*(a[i]-1))) * x;
ans -= tot / 2;
cout << ans << endl;
}
return 0;
}