http://www.spoj.pl/problems/MSKYCODE/
題意:
有N個數,讓你從中選出4個,使得它們的最大公約數爲1 。N<=10000
思路:
用容斥原理來統計數。我們考慮問題的反面,就是先求出所有可能4個數的取法,然後減去4個數的
最大公約數不爲1的組合。
#include<stdio.h>
#include<string.h>
typedef long long LL ;
const int MAXN = 10010 ;
LL N ;
LL d[MAXN] , num[MAXN] , cnt[MAXN];
LL cal( LL n ){
LL res = n * (n - 1LL) * (n - 2LL) * (n - 3LL) / (24LL) ;
return res ;
}
int main(){
LL a;
while( scanf("%lld",&N) == 1){
for(int i=1;i<MAXN;i++){
d[i] = 0 ; //有多少個數能被i整除
num[i] = 0 ; //值爲i的數的個數
cnt[i] = 0 ; //約數爲i的數被計算了幾次
}
for(int i=1;i<=N;i++){
scanf("%lld",&a);
num[a] ++ ;
}
if( N < 4 ){
printf("0\n"); continue ;
}
for(LL i=2;i<MAXN;i++){
for(LL j=i;j<MAXN;j+=i){
d[i] += num[j] ;
}
}
LL tot = 0;
for(LL i=2;i<MAXN;i++){
LL a = 1 - cnt[i] ;
tot += a * cal( d[i] ) ;
for(int j=2*i;j<MAXN;j+=i){
cnt[ j ] += a ;
}
}
printf("%lld\n", cal(N) - tot ) ;
}
return 0 ;
}