bzoj2301 分类: bzoj 2015-05-30 23:14 33人阅读 评论(0) 收藏


莫比乌斯反演+分块优化

PoPoQQQ的课件讲得很详细,大赞~!


#include<map>
#include<stack>
#include<queue>
#include<ctime>
#include<cmath>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<utility>
#include<iostream>
#include<algorithm>

const int SIZE = 50005;

int mu[SIZE], prime[SIZE>>3], tot;
bool check[SIZE];  int sum[SIZE];

void PreWork()
{
    sum[1] = mu[1] = 1;

    for(int i = 2; i < SIZE; i++)   
    {
        if(!check[i]) prime[++tot] = i, mu[i] = -1;

        sum[i] = sum[i-1] + mu[i];

        for(int j = 1, t; j <= tot && (t = prime[j]*i) < SIZE; j++)
        {
            check[t] = true;

            if(i%prime[j]) mu[t] = -mu[i];
            else {mu[t] = 0; break;}
        }
    }   
}

long long Count(int p,int q)
{
//  gcd(i,j)=1 [1,p] [1,q]
    long long ret = 0;

    if(p > q) std::swap(p,q);

    for(int i = 1, next = 0; i <= p; i = next+1)
    {
        next = std::min(p/(p/i), q/(q/i));
        ret += (long long)(sum[next]-sum[i-1])*(p/i)*(q/i);
    }
    return ret;
}

int main()
{
    int n;

#ifndef ONLINE_JUDGE
    freopen("bzoj2301.in","r",stdin);
    freopen("bzoj2301.out","w",stdout);
#endif

    scanf("%d",&n);

    PreWork();

    while(n--)
    {
        int a, b, c, d, k;long long ans;

        scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);

        ans = Count(b/k,d/k) - Count(b/k,(c-1)/k) - Count((a-1)/k,d/k) + Count((a-1)/k,(c-1)/k);

        printf("%lld\n",ans); 
    }



#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-05-30 23:14  <Dash>  阅读(149)  评论(0编辑  收藏  举报