How many integers can you find
Time Limit: 12000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8734 Accepted Submission(s): 2592
Problem Description
Now you get a number N, and a M-integers set, you should find out how many integers which are small than N, that they can divided exactly by any integers in the set. For example, N=12, and M-integer set is {2,3}, so there is another set {2,3,4,6,8,9,10}, all the integers of the set can be divided exactly by 2 or 3. As a result, you just output the number 7.
Input
There are a lot of cases. For each case, the first line contains two integers N and M. The follow line contains the M integers, and all of them are different from each other. 0
#include<cstdio>
#include<cstring>
#define max_n 1010
int p[max_n],cnt;
int gcd(int a,int b){
return b?gcd(b,a%b):a;
}
int lcm(int a,int b){
return a/gcd(a,b)*b;
}
int nop(int n)
{
int sum=0;
for(int i=1;i<(1<<cnt);i++) //二进制实现容斥
{
int res=0,ans=1;
for(int j=0;j<cnt;j++)
{
if((1<<j) & i)
{
res++;
ans=lcm(ans,p[j]);
}
}
if(res & 1)
sum+=n/ans;
else sum-=n/ans;
}
return sum;
}
int main()
{
int n,m,k;
while(scanf("%d %d",&n,&m)!=EOF)
{
cnt=0;
for(int i=0;i<m;i++)
{
scanf("%d",&k);
if(k>=1 && k<n) p[cnt++]=k;//坑点
}
n--; //注意读题,1~n-1
printf("%d\n",nop(n));
}
return 0;
}
队列数组实现容斥,给出的m集合未必都互质,所以求取lcm,但是que数组里面会有负数,则需要加一个abs,然后再把之前的正负号乘上;
#include<cstdio>
#include<cstring>
#define max_n 10010
#include<cmath>
#include<algorithm>
using namespace std;
int p[max_n],cnt;
int gcd(int a,int b){
return b?gcd(b,a%b):a;
}
int lcm(int a,int b){
return a/gcd(a,b)*b;
}
int nop(int n)
{
int que[max_n],top=0,sum=0,pp;
que[top++]=-1;
for(int i=0;i<cnt;i++) //队列数组实现容斥
{
int t=top;
for(int j=0;j<t;j++)
{
if(que[j]<0) pp=-1;
else pp=1;
que[top++]=pp*lcm(abs(que[j]),p[i])*(-1);
}
}
for(int i=1;i<top;i++)
{
sum+=n/que[i];
}
return sum;
}
int main()
{
int n,m,k;
while(scanf("%d %d",&n,&m)!=EOF)
{
cnt=0;
for(int i=0;i<m;i++)
{
scanf("%d",&k);
if(k>=1 && k<n) p[cnt++]=k;//坑点
}
n--; //注意读题,1~n-1
printf("%d\n",nop(n));
}
return 0;
}