P2522 [HAOI2011]Problem b (莫比乌斯反演)

题目

P2522 [HAOI2011]Problem b

解析:

具体推导过程同P3455 [POI2007]ZAP-Queries
不同的是,这个题求的是\(\sum_{i=a}^b\sum_{j=c}^dgcd(i,j)=k\)
像二维前缀和一样容斥一下,输出就完了。

根据luogu某大佬的说法
Screenshot.png
开longlong的话会TLE。。

代码

//莫比乌斯反演 
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int t, n, m, num, k;
int mu[N], p[N], sum[N];
bool vis[N];

template<class T>inline void read(T &x) {
    x = 0; int f = 0; char ch = getchar();
    while (!isdigit(ch)) f |= (ch == '-'), ch = getchar();
    while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
    x = f ? -x : x;
    return;
}

void get_mu(int n) {
    mu[1] = 1;
    for (int i = 2; i <= n; ++i) {
        if (!vis[i]) p[++num] = i, mu[i] = -1;
        for (int j = 1; j <= num; ++j) {
            if (i * p[j] > n) break;
            vis[i * p[j]] = 1;
            if (i % p[j] == 0) {
                mu[i * p[j]] = 0;
                break;
            } else mu[i * p[j]] = -mu[i];
        }
    }
}

int cal(int x, int y, int k) {
    int mx = min(x, y), ans = 0;
    for (int l = 1, r; l <= mx; l = r + 1) {
        r = min(x / (x / l), y / (y / l));
        ans += ((x / (l * k)) * (y / (l * k)) * (sum[r] - sum[l - 1]));
    }
    return ans;
}

int a, b, c, d;

signed main() {
    get_mu(N);
    for (int i = 1; i <= N; ++i) sum[i] = sum[i - 1] + mu[i];
    read(t);
    while (t --) {
        read(a), read(b), read(c), read(d), read(k);
        printf("%d\n", cal(b, d, k) - cal(b, c - 1, k) - cal(a - 1, d, k) + cal(a - 1, c - 1, k));
    }
    return 0;
}

转载于:https://www.cnblogs.com/lykkk/p/10700171.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值