HDU 1695 - GCD (容斥原理)

题意

求1~a中和1~b中最大公倍数为k的二元组数量。

思路

同时除以k,就变成球1~a/k和1~b/k中他们互质的数量,和上一道一样了。

有一些细节要处理,比如k = 0时,和a/k=0时。

代码

#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <cmath>
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define BitCount(x) __builtin_popcount(x)
#define BitCountll(x) __builtin_popcountll(x)
#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
using namespace std;
const double eps = 1e-8;
const int MAXN = 100000 + 10;
const int MOD = 1000007;
const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };  //0123£¬ÉÏÏÂ×óÓÒ
 
typedef pair<int, int> pii;
typedef vector<int>::iterator viti;
typedef vector<pii>::iterator vitii;
 
vector<int> pri[MAXN];
int b, a, vis[MAXN];
 
void GetPrime()
{
    for (int i = 2; i < MAXN; i++)
    {
        if (!vis[i])
        {
            pri[i].PB(i);
            for (int j = i * 2; j < MAXN; j += i)
            {
                vis[j] = 1;
                pri[j].PB(i);
            }
        }
    }
}
int GetPrime(int curNum)
{
    int STATE = (1 << SZ(pri[curNum])), ans = 0;
    for (int curState = 1; curState < STATE; curState++)
    {
        int cnt = 0, pro = 1;
        for (int i = 0; i < SZ(pri[curNum]); i++)
            if ((1 << i) & curState)
            {
                pro *= pri[curNum][i];
                cnt++;
            }
        if (cnt & 1)
        {
            ans += b / pro;
            ans -= curNum / pro;
        }
        else
        {
            ans -= b / pro;
            ans += curNum / pro;
        }
    }
    return b - curNum - ans;
}
 
int main()
{
    //ROP;
    //freopen("output.txt", "r", stdin);
    //freopen("myoutput.txt", "w", stdout);
    GetPrime();
    int T, i, j, cases = 0;
    scanf("%d", &T);
    while (T--)
    {
        int q, qq, k;
        scanf("%d%d%d%d%d", &q, &a, &qq, &b, &k);
        if (k == 0)
        {
            printf("Case %d: 0\n", ++cases);
            continue;
        }
        a /= k, b/= k;
        if (a > b) swap(a, b);
        if (a == 0)
        {
            printf("Case %d: 0\n", ++cases);
            continue;
        }
        LL ans = b;
        for (i = 2; i <= a; i++) ans += GetPrime(i);
        printf("Case %d: %I64d\n",++cases, ans);
    }
    return 0;
}

Powered by Jekyll and Theme by solid