HDU 5072 Coprime 2014 Asia AnShan Regional Contest 容斥




#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
/////
template <class T>
inline bool rd(T &ret) {
	char c; int sgn;
	if(c=getchar(),c==EOF) return 0;
	while(c!='-'&&(c<'0'||c>'9')) c=getchar();
	sgn=(c=='-')?-1:1;
	ret=(c=='-')?0:(c-'0');
	while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');
	ret*=sgn;
	return 1;
}
template <class T>
inline void pt(T x) {
    if (x <0) {
        putchar('-');
        x = -x;
    }
    if(x>9) pt(x/10);
    putchar(x%10+'0');
}
////////
typedef long long ll;
const int N = 100000+1;
const int M = 10000;
bool vis[N];
int prime[M], idx;
int a[N], b[N];

int p[20], idy;
ll G;
void prepare() {
	idx = 0;
	memset(vis, 0, sizeof vis);
	for (int i = 2; i < N; ++i)
		if (!vis[i]) {
			prime[idx++] = i;
			if ((ll)i*i>=N)
				continue;
			for (int j = i*i; j < N; j+= i)
				vis[j] = 1;
		}
}
void dfs(int dep, int get, int sum) {
	if (dep == idy) {
		if (1 == sum)
			return ;
		if (get&1)
			G += b[sum]-1;
		else
			G -= b[sum]-1;

	} else {
		dfs(dep+1, get+1, sum*p[dep]);
		dfs(dep+1, get, sum);
	}
}
void work() {
	memset(vis, 0, sizeof vis);
	ll ans = 0;
	int n, x, cnt, mx = 0;
	rd(n);
	for (int i = 0; i < n; ++i) {
		rd(a[i]);
		vis[a[i]] = 1;
		if (a[i]>mx) mx = a[i];
	}
	b[1] = n;
	for (int i = 2; i <= mx; ++i) {
		cnt = 0;
		for (int j = i; j <= mx; j += i)
			cnt += vis[j];
		b[i] = cnt;
	}
	for (int i = 0; i < n; ++i) {
		idy = 0;
		x = a[i];
		for (int j = 0; j < idx; ++j) {
			if ((ll)prime[j]*prime[j]>a[i])
				break;
			if (a[i] % prime[j] == 0) {
				while (x % prime[j] == 0)
					x /= prime[j];
				p[idy++] = prime[j];
			}
		}
		if (x>1)
			p[idy++] = x;
		G = 0;
		dfs(0, 0, 1);
		ans += G * (n-1-G);
	}
	ans /= 2;
	ans = (ll)n*(n-1)*(n-2)/6 - ans;
	printf("%I64d\n", ans);
}
int main() {
	prepare();
	int T;
	scanf("%d", &T);
	while (T-->0)
		work();
	return 0;
}


你可能感兴趣的:(HDU 5072 Coprime 2014 Asia AnShan Regional Contest 容斥)