HDU 6053 TrickGCD(莫比烏斯反演+字首和)
TrickGCD
Time Limit: 5000/2500 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 3226 Accepted Submission(s): 1206
Problem Description
You are given an array A , and Zhu wants to know there are how many different array B satisfy the following conditions?
- 1≤Bi≤Ai
- For each pair( l , r ) (1≤l≤r≤n) , gcd(bl,bl+1…br)≥2
Input
The first line is an integer T(1≤T≤10) describe the number of test cases.
Each test case begins with an integer number n describe the size of array A.
Then a line contains n numbers describe each element of A
You can assume that 1≤n,Ai≤105
Output
For the kth test case , first output “Case #k: ” , then output an integer as answer in a single line . because the answer may be large , so you are only need to output answer mod 109+7
Sample Input
1
4
4 4 4 4
Sample Output
Case #1: 17
題意:給你一個A陣列,求B陣列的個數,B陣列要滿足這幾個條件
Bi≤Ai
Gcd(B1,B2,…..,Bn)≥2
思路:易發現答案是列舉gcd從2開始到ai中最小的數的數量
那麼我們可以從2開始列舉gcd,ai/gcd就是比ai小的數裡面有幾個數含有gcd為因子的數所以也就是
這個式子
直接一個一個計算的話會超時,那麼我們發現3-5除於3的值都是1,而且當其越大這個區間也就越大,我們可以利用字首和的方法來減少時間
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
const int mod=1000000007;
using namespace std;
const int maxn=100005;
int prime[maxn];
int mu[maxn];
bool vis[maxn];
int cnt;
int sum[maxn];
void Init(){
int N=maxn;
memset(prime,0,sizeof(prime));
memset(mu,0,sizeof(mu));
memset(vis,0,sizeof(vis));
mu[1] = 1;
cnt = 0;
for(int i=2; i<N; i++){
if(!vis[i]){
prime[cnt++] = i;
mu[i] = -1;
}
for(int j=0; j<cnt&&i*prime[j]<N; j++){
vis[i*prime[j]] = 1;
if(i%prime[j]) mu[i*prime[j]] = -mu[i];
else{
mu[i*prime[j]] = 0;
break;
}
}
}
}
long long quickmod(long long a,long long n)
{
long long ans=1;
a=a%mod;
while(n>0)
{
if(n%2==1)
ans=ans*a%mod;
n/=2;
a=a*a%mod;
}
return ans;
}
int main()
{
Init();
int t,cas=1;
scanf("%d",&t);
while(t--)
{
memset(sum,0,sizeof(sum));
int n;
scanf("%d",&n);
int min1=mod;
for(int i=1;i<=n;i++)
{
int x;
scanf("%d",&x);
sum[x]++;
min1=min(min1,x);
}
for(int i=1;i<maxn;i++) sum[i]+=sum[i-1];
long long ans=0;
for(int i=2;i<=min1;i++)
{
long long temp=1;
for(int j=i;j<maxn;j+=i)
temp=temp*quickmod(j/i,sum[min(j+i-1,maxn-1)]-sum[j-1])%mod;
ans=(ans+temp*mu[i]*-1+mod)%mod;
}
printf("Case #%d: ",cas++);
printf("%lld\n",ans);
}
return 0;
}