2 1 10 2 3 15 5
Case #1: 5 Case #2: 10HintIn the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.
The Third Lebanese Collegiate Programming Contest
题目大意:在区间[A,B]中计算出与N互素的数的数量。
思路:因为直接算互素有点麻烦,所以可以先算不互素的,然后总的数减去不互素的,剩下就是答案了。对于不互素的数求法,可以先算出N的质因数xn,然后在[A,B]中寻找xn的倍数,这就是不互素的数目了。但是直接减去是错误的,因为这中间会有重复。
举个例子:假如N的质因数有2和3,在[A,B]中寻找时可以找到6为2和3的倍数,这样就有2个了,实际上一个就够了。
这里就要用容斥原理了:在上述过程中要把为6的倍数去掉。
#include<stdio.h>
#include<string.h>
#include<math.h>
#define LL __int64
LL p[100];
LL dfs(LL n,LL b,LL x,LL k)
{
LL i,j,ans=0;
for(i=x;i<=k;i++)
{
ans+=b/p[i]-dfs(n,b/p[i],i+1,k);
}
return ans;
}
int main()
{
int T,t;
LL a,b,n,i,j,k,x,ans;
scanf("%d",&T);
t=0;
while(T--)
{
t++;
k=0;
ans=0;
scanf("%I64d%I64d%I64d",&a,&b,&n);
x=n;
for(i=2;i<=sqrt(n);i++)
{
if(x%i==0){
while(x%i==0)x=x/i;
p[++k]=i;
}
}
if(x>1)p[++k]=x;
ans=b-a+1-dfs(n,b,1,k)+dfs(n,a-1,1,k);
printf("Case #%d: %I64d\n",t,ans);
}
return 0;
}
2 1 1 2 3
1 5
这题跟上面那题一样,只是要先预处理出来,否则会TLE。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<vector>
#include<math.h>
#define LL __int64
using namespace std;
int n,m;
struct node{
LL num[105];
}p[100005];
vector<int>ps[100005];
int len[100005];
void initi(){
LL i,j,x,k=0;
for(i=1;i<=100000;i++)
{
x=i;k=0;
for(j=2;j<=sqrt(i);j++)
{
if(x%j==0){
while(x%j==0)
x=x/j;
ps[i].push_back(j);
}
}
if(x>1)ps[i].push_back(x);
}
}
LL dfs(LL s,LL b,LL x,LL k)
{
LL ans=0;
int i;
for(i=x;i<k;i++)
{
ans+=b/ps[s][i]-dfs(s,b/ps[s][i],i+1,k);
}
return ans;
}
int main()
{
int T,t;
LL x,ans;
int i,j,k;
initi();
scanf("%d",&T);
t=0;
while(T--)
{
t++;
k=0;
ans=0;
scanf("%d%d",&n,&m);
for(i=1;i<=m;i++)
{
// printf("%I64d\n",len[i]);
ans+=n-dfs(i,n,0,ps[i].size());
}
printf("%I64d\n",ans);
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
hdu 4135 Co-prime +hdu 2841 Visible Trees(容斥原理)
原文:http://blog.csdn.net/aaaaacmer/article/details/47319911