Codeforces 839DWinter is here

 
Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.
He has created a method to know how strong his army is. Let the i-th soldier’s strength be ai. For some k he calls i1, i2, ..., ik a clan if i1 < i2 < i3 < ... < ik and gcd(ai1, ai2, ..., aik) > 1 . He calls the strength of that clan 
k·gcd(ai1, ai2, ..., aik). Then he defines the strength of his army by the sum of strengths of all possible clans. Your task is to find the strength of his army. As the number may be very large, you have to print it modulo 1000000007 (109 + 7). Greatest common divisor (gcd) of a sequence of integers is the maximum possible integer so that each element of the sequence is divisible by it. Input The first line contains integer n (1 ≤ n ≤ 200000) — the size of the army. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000000) — denoting the strengths of his soldiers. Output Print one integer — the strength of John Snow's army modulo 1000000007 (109 + 7). Examples inputCopy 3 3 3 1 outputCopy 12 inputCopy 4 2 3 4 outputCo 39 Note In the first sample the clans are {1}, {2}, {1, 2} so the answer will be 1·3 + 1·3 + 2·3 = 12

题意:给出一个序列,求其中所有 gcd 大于 1 的子序列gcd乘以序列长度之和

思路:对于某一个因数X,可以求出他的倍数X,2X,3X...,设他们的个数总和为n。这样求sum[x](最大公因数为x的所有数的序列长度和)时

有sum[x]=1*C(1,n)+2*C(2,n)+...+n*C(n,n)=n*2^(n-1)。但是2X和4X的最大公因数并不是X而是2X,这样答案还有多余,所以sum[x]=sum[x]-sum[2x]-sum[3x]-...

这样只需从n到1遍历X即可,最后ans+=X*sum[X];

/*
11111111
00000110
00001100
00011000
00110000
01100000
*/
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<map>
#include<vector>
#define pb push_back
#define ll long long
const int inf=0x3f3f3f3f;
using namespace std;
const int N=1e6+5;
const ll mod=1e9+7;
int n,x;
ll sum[N],cnt[N];
ll quickpow(int x,ll ci)
{
    ll an=1;
    ll res=x;
    while(ci>0)
    {
        if(ci&1)
        {
            an=an*res%mod;
        }
        res=(res*res)%mod;
        ci=ci>>1;
    }
    return an;
}
int main()
{
    //printf("%lld\n",quickpow(2,0));
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&x);
        cnt[x]++;
    }
    ll k;
    ll ans=0;
    for(int i=1000000;i>1;i--)
    {
        k=0;
        for(int j=i;j<=1000000;j+=i)
        {
            k+=cnt[j];
            sum[i]=(sum[i]-sum[j]+mod)%mod;
        }
        sum[i]=(sum[i]+k*quickpow(2,k-1)%mod)%mod;
        ans=(ans+i*sum[i])%mod;
    }
    printf("%lld\n",ans);
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/switch-waht/p/12212476.html
今日推荐