洛谷:3455 [POI2007]ZAP-Queries

洛谷:3455 [POI2007]ZAP-Queries

题意描述

  • \(50000\)组询问,每次给定三个整数\(a,b,d\)问有多少二元组\((x,y)\)满足\(x\leq a,y\leq b \ and \ gcd(x,y) =d\).
  • \(a,b\leq 50000\)

思路

  • 莫比乌斯反演
  • \(f(k)\)\(gcd(i,j)==k\)的个数:\(f(k)=\sum_{i=1}^a\sum_{j=1}^b[gcd(i,j)=k]\)
  • \(F(n)\)\(gcd(i,j)==cnt*n\)的个数,其中\(cnt=1,2,...\)
  • \(F(n)=\sum_{n|k}f(k)=\frac{a}{n}\frac{b}{n}\)
  • 反演得:\(f(n)=\sum_{n|k}\mu(\frac{k}{n})*F(k)\)
  • 可以知道,答案就是\(f(d)=ans=\sum_{d|k}\mu(\frac{k}{d})F(k)\)
  • 之后枚举\(\frac{k}{d}=t,\)原式改写为\(ans=\sum_{t=1}^{min\{\frac{a}{d}\frac{b}{d}\}}\mu(t)\frac{a}{td}\frac{b}{td}\)
  • 这时候可以做到\(O(n)\)的复杂度,但是由于多组数据,采用分块优化至\(O(\sqrt{n})\)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5e4 + 100;
int mu[maxn], primes[maxn], cnt, sum[maxn], T;
bool vis[maxn];

template<typename T>inline void read(T &x)
{
    x=0;
    static int p;p=1;
    static char c;c=getchar();
    while(!isdigit(c)){if(c=='-')p=-1;c=getchar();}
    while(isdigit(c)) {x=(x<<1)+(x<<3)+(c-48);c=getchar();}
    x*=p;
}

void get_mu(int n)
{
    mu[1] = 1;
    for(int i = 2; i <= n; i++)
    {
        if(!vis[i])
        {
            primes[++cnt] = i;
            mu[i] = -1;
        }
        for(int j = 1; primes[j] <= n/i; j++)
        {
            vis[primes[j]*i] = 1;
            if(i % primes[j] == 0) break;
            else mu[i*primes[j]] = -mu[i];
        }
    }
    for(int i = 1; i <= n; i++)
        sum[i] = sum[i-1] + mu[i];
}


inline void solve(int n, int m)
{
    if(n > m) swap(n, m);
    int ans = 0;
    for(int l = 1, r; l <= n; l = r+1)
    {
        r = min(n/(n/l), m/(m/l));
        ans += (ll)((n/l)*(m/l) * (sum[r] - sum[l-1]));
    }printf("%lld\n", ans);
}

int main()
{
    get_mu(50000+5);
    read(T);
    while(T--)
    {
        int a, b, d;
        read(a); read(b); read(d);
        solve(a/d, b/d);
    }
    return 0;
}

posted @ 2020-01-08 19:40  zhaoxiaoyun  阅读(117)  评论(0编辑  收藏  举报