BZOJ 2301 Problem b (莫比乌斯反演)

题目链接:https://cn.vjudge.net/problem/HYSBZ-2301

思路:令f(k)表示gcd(x, y) == k的数对的个数,令F(k)表示gcd(x, y) % k == 0的数对的个数。易知F(k) = ∑f(d) (k | d),且F(k) = (a / k) * (b / k ),由莫比乌斯反演可得f(k) = ∑( u(d/k) * F(d) ) = ∑( u(d/k) * (a/d) * (b/d)),注意到在某个区间[i, j]内,对任意的x∈[i, j],(a/x) * (b/x)的值都相等。因此我们可以把这一段区间一次性一起算上来达到节省时间的目的。


#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<cmath>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#define fin(a) freopen("a.txt","r",stdin)
#define fout(a) freopen("a.txt","w",stdout)
typedef long long LL;
using namespace std;
typedef pair<int, int> P;
const int dx[] = {0, 0, 0, -1, 1};
const int dy[] = {0, -1, 1, 0, 0};
const int INF = 1e8 + 10;
const int maxn = 5e5 + 10;
int prime[maxn], mu[maxn], sum[maxn];
bool check[maxn];

void getMu() {
   mu[1] = 1;
   int tot = 0;
   for(int i = 2; i < maxn; i++) {
      if(!check[i]) { prime[tot++] = i; mu[i] = -1; }
      for(int j = 0; j < tot; j++) {
         if(i * prime[j] > maxn) break;
         check[i * prime[j]] = true;
         if(i % prime[j] == 0) {
            mu[i * prime[j]] = 0;
            break;
         }
         else {
            mu[i * prime[j]] = -mu[i];
         }
      }
   }
   for(int i = 1; i < maxn; i++)
      sum[i] = sum[i-1] + mu[i];
}

LL solve(int n, int m) {
   if(n > m) swap(n, m);
   LL ans = 0, pos;
   for(int i = 1; i <= n; i = pos + 1) {
      pos = min(n/(n/i), m/(m/i));
      ans += (sum[pos] - sum[i-1]) * LL(n/i) * LL(m/i);
   }
   return ans;
}

int main() {
   getMu();
   int T;
   scanf("%d", &T);
   while(T--) {
      int a, b, c, d, k;
      scanf("%d%d%d%d%d", &a, &b, &c, &d, &k);
      if(!k) { printf("0\n"); continue; }
      LL ans = solve(b/k, d/k) - solve((a-1)/k, d/k) - solve((c-1)/k, b/k) + solve((a-1)/k, (c-1)/k);
      printf("%lld\n", ans);
   }
}

 
发布了121 篇原创文章 · 获赞 8 · 访问量 4万+
展开阅读全文

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

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览