HDU 1695 GCD(gcd(x,y)=k无序对数/容斥原理)

题目链接:
HDU 1695 GCD
题意:
x[a,b],y[c,d]gcd(x,y)=k(x,y)a=c=1
分析:
和BZOJ 2301的区别就是这里是无序对。
bd,,x[1,b],y[1,b] 还要注意每次计算都是计算有序的!

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
const int MAX_N = 100010;

int T, cases = 0, a, b, c, d, k, prime_cnt;
int mu[MAX_N], vis[MAX_N], prime[MAX_N];

void init()
{
    prime_cnt = 0;
    mu[1] = 1;
    memset(vis, 0, sizeof(vis));
    for(int i = 2; i < MAX_N; i++) {
        if(vis[i] == 0) {
            prime[prime_cnt++] = i;
            mu[i] = -1;
        }
        for(int j = 0; j < prime_cnt && i * prime[j] < MAX_N; j++) {
            vis[i * prime[j]] = 1;
            if(i % prime[j] ) {
                mu[i * prime[j]] = -mu[i];
            }else {
                mu[i * prime[j]] = 0;
                break;
            }
        }
    }
}

ll solve(int n, int m)
{
    ll res = 0;
    int low = min(n, m);
    for(int i = 1; i <= low; ++i) {
        res += (ll)mu[i] * (n / i) * (m / i);
    }
    ll tmp = 0;
    for(int i = 1; i <= low; ++i) {
        tmp += (ll)mu[i] * (low / i) * (low / i);
    }   
    res -= tmp / 2;
    return res;
}

int main()
{
    init();
    scanf("%d", &T);
    while(T--) {
        scanf("%d%d%d%d%d", &a, &b, &c, &d, &k);
        if(k == 0) {
            printf("Case %d: 0\n", ++cases);
            continue;
        }
        b /= k, d /= k;
        printf("Case %d: %lld\n", ++cases, solve(b, d));
    }
    return 0;
}

你可能感兴趣的:(容斥原理,莫比乌斯反演,HDU,HDU,莫比乌斯反演,容斥原理)