BZOJ1101 [POI2007]Zap 【莫比乌斯反演】

1101: [POI2007]Zap

Time Limit: 10 Sec Memory Limit: 162 MB
Submit: 2813 Solved: 1213
[Submit][Status][Discuss]
Description

  FGD正在破解一段密码,他需要回答很多类似的问题:对于给定的整数a,b和d,有多少正整数对x,y,满足x<=a
,y<=b,并且gcd(x,y)=d。作为FGD的同学,FGD希望得到你的帮助。

Input

  第一行包含一个正整数n,表示一共有n组询问。(1<=n<= 50000)接下来n行,每行表示一个询问,每行三个
正整数,分别为a,b,d。(1<=d<=a,b<=50000)

Output

  对于每组询问,输出到输出文件zap.out一个正整数,表示满足条件的整数对数。

Sample Input

2

4 5 2

6 4 3
Sample Output

3

2

//对于第一组询问,满足条件的整数对有(2,2),(2,4),(4,2)。对于第二组询问,满足条件的整数对有(

6,3),(3,3)。

题解

ans=ai=1bj=1[gcd==d]
=adi=1bdj=1[gcd(i,j)==1]
=adi=1μ(i)aibi
分块
总的O(na)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define Redge(u) for (int k = h[u]; k != -1; k = ed[k].nxt)
using namespace std;
const int maxn = 50005,maxv = 50000,INF = 1000000000;
inline int RD(){
    int out = 0,flag = 1; char c = getchar();
    while (c < 48 || c > 57) {if (c == '-') flag = -1; c = getchar();}
    while (c >= 48 && c <= 57) {out = (out << 1) + (out << 3) + c - '0'; c = getchar();}
    return out * flag;
}
int prime[maxn],primei = 0,mu[maxn];
bool isn[maxn];
void cal(){
    mu[1] = 1;
    for (int i = 2; i <= maxv; i++){
        if (!isn[i]) prime[++primei] = i,mu[i] = -1;
        for (int j = 1; j <= primei && i * prime[j] <= maxv; j++){
            isn[i * prime[j]] = true;
            if (i % prime[j] == 0) {mu[i * prime[j]] = 0; break;}
            mu[i * prime[j]] = -mu[i];
        }
    }
    REP(i,maxv) mu[i] += mu[i - 1];
}
int main(){
    cal();
    int n = RD(),N,M,d; int ans;
    while (n--){
        N = RD(); M = RD(); d = RD(); ans = 0;
        if (N > M) swap(N,M);
        N /= d; M /= d;
        for (int i = 1,nxt; i <= N; i = nxt + 1){
            nxt = min(N / (N / i),M / (M / i));
            ans += (N / i) * (M / i) * (mu[nxt] - mu[i - 1]);
        }
        printf("%d\n",ans);
    }
    return 0;
}
posted @ 2017-12-18 14:02  Mychael  阅读(133)  评论(0编辑  收藏  举报