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

把一个询问拆成4个:

i=1bj=1d[gcd(i,j)=k]

i=1a1j=1d[gcd(i,j)=k]

i=1bj=1c1[gcd(i,j)=k]

i=1a1j=1c1[gcd(i,j)=k]

然后就是莫比乌斯反演的经典模型i=1nj=1m[gcd(i,j)=t]了。
具体见:http://blog.csdn.net/xyz32768/article/details/79218250
代码:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
    int res = 0; bool bo = 0; char c;
    while (((c = getchar()) < '0' || c > '9') && c != '-');
    if (c == '-') bo = 1; else res = c - 48;
    while ((c = getchar()) >= '0' && c <= '9')
        res = (res << 3) + (res << 1) + (c - 48);
    return bo ? ~res + 1 : res;
}
typedef long long ll;
const int N = 5e4;
int pri[N + 5], miu[N + 5], sum[N + 5], cnt;
bool is[N + 5];
void sieve() {
    int i, j; miu[1] = 1; is[0] = is[1] = 1;
    for (i = 2; i <= N; i++) {
        if (!is[i]) pri[++cnt] = i, miu[i] = -1;
        for (j = 1; j <= cnt; j++) {
            if (1ll * i * pri[j] > N) break;
            is[i * pri[j]] = 1;
            if (i % pri[j] == 0) break;
            else miu[i * pri[j]] = -miu[i];
        }
    }
    for (i = 1; i <= N; i++) sum[i] = sum[i - 1] + miu[i];
}
ll solve(int n, int m) {
    if (!n || !m) return 0ll;
    int i, nxt; ll ans = 0;
    for (i = 1; i <= min(n, m);) {
        nxt = min(n / (n / i), m / (m / i));
        ans += 1ll * (sum[nxt] - sum[i - 1]) * (n / i) * (m / i);
        i = nxt + 1;
    }
    return ans;
}
int main() {
    int T = read(), a, b, c, d, k; sieve();
    while (T--) {
        a = read(); b = read(); c = read();
        d = read(); k = read();
        printf("%lld\n", solve(b / k, d / k) - solve((a - 1) / k, d / k)
            - solve(b / k, (c - 1) / k) + solve((a - 1) / k, (c - 1) / k));
    }
    return 0;
}
发布了410 篇原创文章 · 获赞 53 · 访问量 7万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 创作都市 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览