POJ 3904:Sky Code _容斥原理

Sky Code
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 585   Accepted: 163

Description

Stancu likes space travels but he is a poor software developer and will never be able to buy his own spacecraft. That is why he is preparing to steal the spacecraft of Petru. There is only one problem – Petru has locked the spacecraft with a sophisticated cryptosystem based on the ID numbers of the stars from the Milky Way Galaxy. For breaking the system Stancu has to check each subset of four stars such that the only common divisor of their numbers is 1. Nasty, isn’t it? Fortunately, Stancu has succeeded to limit the number of the interesting stars to N but, any way, the possible subsets of four stars can be too many. Help him to find their number and to decide if there is a chance to break the system.

Input

In the input file several test cases are given. For each test case on the first line the number N of interesting stars is given (1 ≤ N ≤ 10000). The second line of the test case contains the list of ID numbers of the interesting stars, separated by spaces. Each ID is a positive integer which is no greater than 10000. The input data terminate with the end of file.

Output

For each test case the program should print one line with the number of subsets with the asked property.

Sample Input

4
2 3 4 5 
4
2 4 6 8 
7
2 3 4 5 7 6 8

Sample Output

1 
0 
34

Source

Southeastern European Regional Programming Contest 2008

//题意,给出n个数,问有多少组(a,b,c,d)公约数为1,注意并不一定两两互质!因为不一定两两都互质,那么从相反的方向着手比较方便!即先统计出(a,b,c,d)公约数>1的对数,然后用总数减去即可!

容斥原理应用,以2为因子的数有a个,3为因子 的数有b个,6为因子的数有c个,n个数不互质的四元组个数为C(4,a)+C(4,b)-C(4,c) (含奇数个素因子的加,偶数个素因子的减),下面就是统计出2,3,5这些因子的倍数的个数,对C(4,a)容斥!


#include<stdio.h>
#include<string.h>
using namespace std;
#define LL long long
#define maxn 10005

LL node[maxn],num[maxn],vist[maxn],prime[maxn];
void Init()
{
	LL i;
	for(i=4;i<maxn;i++)
		node[i]=i*(i-1)*(i-2)*(i-3)/24;
}

void make_count(int m)
{
	int i,j,tmp,flag,cnt=0;
	for(i=2;i*i<=m;i++)
		if(m&&m%i==0)
		{
			prime[cnt++]=i;
			while(m&&m%i==0)
				m/=i;
		}	
	if(m>1)
		prime[cnt++]=m;
	for(i=1;i<(1<<cnt);i++)
	{
		tmp=1,flag=0;
		for(j=0;j<cnt;j++)
			if(i&(1<<j))
				flag++,tmp*=prime[j];
		num[tmp]++;  //统计当前因子出现的次数
		vist[tmp]=flag; //记录当前因子是由多少个素因子组成,奇加偶减
	}
}

int main()
{
	Init();
	int n,i,x;
	while(~scanf("%d",&n))
	{
		memset(num,0,sizeof(num));
		memset(vist,0,sizeof(vist));
		for(i=0;i<n;i++)
		{
			scanf("%d",&x);
			make_count(x);
		}
		LL ans=0;
		for(i=1;i<maxn;i++)
			if(num[i])
			{
				if(vist[i]&1)
					ans+=node[num[i]];
				else
					ans-=node[num[i]];
			}
		printf("%I64d\n",node[n]-ans);			
	}
	return 0;
}


你可能感兴趣的:(Integer,System,input,each,output,Numbers)