0
点赞
收藏
分享

微信扫一扫

POJ3904 Sky Code【容斥原理】


题目链接:

​​http://poj.org/problem?id=3904​​


题目大意:

给你N个整数,从这N个数中选择4个数,使得这四个数的公约数为1。求满足条件的

四元组个数。


解题思路:

四个数的公约数为1,并不代表四个数两两互质。比如(2,3,4,5)公约数为1,但是

2和4并不互质。从反面考虑,先求出四个数公约数不为1的情况个数,用总的方案个数

减去四个数公约数不为1的情况个数就是所求。

求四个数公约数不为1的情况个数,需要将N个数每个数质因数分解,纪录下所有不同

的素因子所能组成的因子(就是4个数的公约数),并统计构成每种因子的素因子个数,

和因子总数。然后再计算组合数。比如说因子2的个数为a,则四个数公约数为2的个数

为C(a,4),因子3的个数为b,则四个数公约数为3的个数为C(b,4),因子6(2*3)的个

数为c,则四个数公约数的个数为C(c,4)。

但是公约数为2的情况中或者公约数为3的情况中可能包括公约数为6的情况,相当于几

个集合求并集,这就需要容斥定理来做。具体参考代码。


AC代码:


#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#define LL __int64
using namespace std;

LL C(LL N) //计算 C(N,4)
{
return N * (N-1) * (N-2) * (N-3) / 24;
}

LL Factor[10010],ct,Count[10010],Num[10010];
//Count[]纪录当前因子的个数,Num[]纪录当前因子是由几个素因子组成(用于容斥定理的奇加偶减)
void Divide(LL N) //将N分解质因数
{
ct = 0;
for(int i = 2; i <= sqrt(N*1.0); ++i)
{
if(N % i == 0)
{
Factor[ct++] = i;
while(N % i == 0)
N /= i;
}
}
if(N != 1)
Factor[ct++] = N;
}

void Solve(LL N) //二进制实现容斥原理
{
Divide(N);
for(int i = 1; i < (1 << ct); ++i)
{
LL tmp = 1;
LL odd = 0;
for(int j = 0; j < ct; ++j)
{
if((1 << j) & i)
{
odd++;
tmp *= Factor[j];
}
}
Count[tmp]++;
Num[tmp] = odd;
}
}

int main()
{
LL N,M;
while(~scanf("%I64d",&N))
{
memset(Count,0,sizeof(Count));
for(int i = 0; i < N; ++i)
{
scanf("%I64d",&M);
Solve(M);
}
LL ans = 0;
for(int i = 0; i <= 10000; ++i) //容斥
{
if(Count[i])
{
if(Num[i] & 1)
ans += C(Count[i]);
else
ans -= C(Count[i]);
}
}
printf("%I64d\n",C(N) - ans); //结果为C(N,4) - ans
}

return 0;
}




举报

相关推荐

0 条评论