您的位置:首页 > 大数据 > 人工智能

[莫比乌斯函数][分段] hdu6053 TrickGCD (2017 Multi-University Training Contest - Team 2)

2017-07-28 14:09 489 查看
@(ACM题目)[莫比乌斯]

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

题目分析

本题给定一个长度为n的数组{ai},现要构造一个新数组{bi},使其符合下列全部要求:

- {ai}与{bi}长度相同,且新数组对应元素小于等于原数组,即bi≤ai

- 整个新数组的gcd≥2

易得答案为:

∑i=2min(a)−μ(i)∏j=1n⌊aji⌋

求解该式需要以下两方面:

莫比乌斯函数

μ(d)为莫比乌斯函数,其定义如下:

- 若d=1,μ(d)=1

- 若d=p1p2…pk,pi为互异素数,μ(d)=(−1)k

- 其他情况μ(d)=0

我们可以莫比乌斯函数方便地进行容斥

分段

对于上式中一个特定的i,我们可以将⌊aji⌋为一个特定的值k的一段通过前缀和+快速幂快速地计算出来。

k=⌊aji⌋说明aj的值在[ki,ki+i−1]之间,用前缀和可以算出符合条件的aj有m个,则其在∏nj=1⌊aji⌋中的贡献为km,这个值可以用快速幂求得。

如果你蜜汁TLE了,请注意前缀和数组要开2e5而不是1e5,因为下标最大访问到ki+i−1

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 2e5+8;
const int M = 1e9+7;
bitset<maxn> isPrime;
int sum[maxn], primes[maxn], mu[maxn], tot = 0;
void mobius()
{
isPrime.set();
isPrime[1] = 0;
mu[1] = 1;
tot = 0;
for(int i = 2; i < 100005; ++i)
{
if(isPrime.test(i)) primes[tot++] = i, mu[i] = -1;
int d;
for(int j = 0; j < tot && (d = i * primes[j]) < maxn; ++j)
{
isPrime[d] = false;
if(i % primes[j]) mu[d] = -mu[i];
else
{
mu[d] = 0;
break;
}
}
}
}

LL pow_m(LL a, LL n, LL M)
{
a %= M;
LL res = 1;
while(n > 0)
{
if(n & 1) res = res*a%M;
a = a * a % M;
n >>= 1;
}
return res;
}

int main()
{
mobius();
int T, Case = 1;
cin >> T;
while(T--)
{
int n;
scanf("%d", &n);
int mn = 1e5+5, mx = -1;
memset(sum, 0, sizeof sum);
for(int i = 0; i < n; ++i)
{
int x;
scanf("%d", &x);
++sum[x];
if(mn > x) mn = x;
if(mx < x) mx = x;
}
for(int i = 1; i < maxn; ++i) sum[i] += sum[i-1];
LL res = 0;
for(int i = 2; i <= mn; ++i)
{
if(!mu[i]) continue;
LL tmp = 1;
for(int j = 1; i*j <= mx; ++j)
tmp = tmp * pow_m(j, sum[i*j + (i-1)] - sum[i*j - 1], M) % M;
res = (res - mu[i] * tmp + M) % M;
}
printf("Case #%d: %lld\n", Case++, res);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息