HDU 1695 容斥原理

#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1E5 + 10;
std::vector<int> v[maxn];
int T, A, B, C, D, K, kase;
void init()
{
	for (int i = 2; i < maxn; i += 2) v[i].push_back(2);
	for (int i = 3; i < maxn; i += 2)
		if (!v[i].size())
			for (int j = i; j < maxn; j += i)
				v[j].push_back(i);
}
long long solve(int x)
{
	long long sum = 0, tmp, cnt;
	for (int i = 1; i < (1 << v[x].size()); i++)
	{
		tmp = 1, cnt = 0;
		for (int  j = 0; j < v[x].size(); j++)
			if (i & (1LL << j)) tmp *= v[x][j], cnt++;
		sum += (cnt & 1 ? -1 : 1) * min(x, B) / tmp;
	}
	return min(x, B) + sum;
}
int main(int argc, char const *argv[])
{
	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", ++kase);
		else
		{
			B /= K, D /= K;
			if (B > D) swap(B, D);
			long long ans = 0;
			for (int i = 1; i <= D; i++)
				ans += solve(i);
			printf("Case %d: %lld\n", ++kase, ans);
		}
	}
	return 0;
}


和HDU 4135 基本一样。

(1,b)区间和(1,d)区间里面gcd(x, y) = k的数的对数.

即为(1,b/k)和(1,d/k)区间里面gcd(x,y) = 1 的对数。

求出来减一下。

你可能感兴趣的:(HDU 1695 容斥原理)