HDU 5072Coprime

来源:互联网 发布:hdfs数据删除如何恢复 编辑:程序博客网 时间:2024/04/30 08:15

Description

There are n people standing in a line. Each of them has a unique id number. 

Now the Ragnarok is coming. We should choose 3 people to defend the evil. As a group, the 3 people should be able to communicate. They are able to communicate if and only if their id numbers are pairwise coprime or pairwise not coprime. In other words, if their id numbers are a, b, c, then they can communicate if and only if [(a, b) = (b, c) = (a, c) = 1] or [(a, b) ≠ 1 and (a, c) ≠ 1 and (b, c) ≠ 1], where (x, y) denotes the greatest common divisor of x and y. 

We want to know how many 3-people-groups can be chosen from the n people.

Input

The first line contains an integer T (T ≤ 5), denoting the number of the test cases. 

For each test case, the first line contains an integer n(3 ≤ n ≤ 10 5), denoting the number of people. The next line contains n distinct integers a 1, a 2, . . . , a n(1 ≤ a i ≤ 10 5) separated by a single space, where a i stands for the id number of the i-th person.

Output

For each test case, output the answer in a line.

Sample Input

151 3 9 10 2

Sample Output

4


求问题的反面,用容斥原理搞定。

#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<iostream>#include<queue>using namespace std;const int N = 1e5+5;int T,n,a[N];int f[N],p[N],mu[N],t;int g[N];void gao(){    mu[1]=f[1]=1;    for (int i=2;i<N;i++)    {        if (!f[i]) p[t++]=i,mu[i]=-1;        for (int j=0,k;j<t&&p[j]*i<N;j++)        {            f[k=p[j]*i]=1;            mu[k]=mu[i]*-1;            if (i%p[j]==0) {mu[k]=0; break;}        }    }}int main(){    gao();    scanf("%d",&T);    while(T--)    {        scanf("%d",&n);        memset(g,0,sizeof(g));        for (int i=1;i<=n;i++)        {            scanf("%d",&a[i]);            for (int j=1;j*j<=a[i];j++)            {                if (a[i]%j) continue;                g[j]++;                if (j*j!=a[i]) g[a[i]/j]++;            }        }        long long res=0;        for (int i=1;i<=n;i++)        {            int ans=0;            for (int j=1;j*j<=a[i];j++)            {                if (a[i]%j) continue;                ans+=g[j]*mu[j];                if (j*j!=a[i])                {                    ans+=mu[a[i]/j]*g[a[i]/j];                }            }            if (a[i]==1) continue;            res+=1LL*ans*(n-ans-1);        }        printf("%lld\n",1LL*n*(n-1)*(n-2)/6-res/2);    }    return 0;}


0 0
原创粉丝点击