1. 程式人生 > 實用技巧 >洛谷 p3455 [POI2007]ZAP-Queries

洛谷 p3455 [POI2007]ZAP-Queries

題意:

給定$a, b, d$,求滿足$1 \leq x \leq a , 1 \leq y \leq b$且$\gcd(x, y)=d$的二元組${x, y)$的數量

思路:

$\sum_{x=1}^{n}\sum_{y=1}^{b}[\gcd(x, y)=d]$

簡化式子:

$\sum_{x=1}^{\lfloor\frac{a}{d}\rfloor}\sum_{y=1}^{\lfloor\frac{b}{d}\rfloor}[\gcd(x, y)=1]$

將$[\gcd(x, y) = 1]$替換為$\varepsilon(\gcd(x, y))$:

$\sum_{x=1}^{\lfloor\frac{a}{d}\rfloor}\sum_{y=1}^{\lfloor\frac{b}{d}\rfloor}\varepsilon(\gcd(x, y))$

展開$\varepsilon$函式得到:

$\sum_{x=1}^{\lfloor\frac{a}{d}\rfloor}\sum_{y=1}^{\lfloor\frac{b}{d}\rfloor}\sum_{k|\gcd(x,y)} \mu(k)$

變換求和順序,先列舉$k|\gcd(x, y)$得:

$\sum_{k=1}\mu(k)\sum_{x=1}^{\lfloor\frac{a}{d}\rfloor}[k|x]\sum_{y=1}^{\lfloor\frac{b}{d}\rfloor}[k|y]$

已知$1~\lfloor\frac{a}{d}\rfloor$中$k$的倍數有$\lfloor\frac{a}{kd}\rfloor$個:

$\sum_{k=1}\mu(k)\lfloor\frac{a}{kd}\rfloor\lfloor\frac{b}{kd}\rfloor$

Code;

#pragma GCC optimize(3)
#pragma GCC optimize(2)
#include <map>
#include <set>
// #include <array>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include 
<cstring> #include <sstream> #include <iostream> #include <stdlib.h> #include <algorithm> // #include <unordered_map> using namespace std; typedef long long ll; typedef pair<int, int> PII; #define Time (double)clock() / CLOCKS_PER_SEC #define sd(a) scanf("%d", &a) #define sdd(a, b) scanf("%d%d", &a, &b) #define slld(a) scanf("%lld", &a) #define slldd(a, b) scanf("%lld%lld", &a, &b) const int N = 1e5 + 20; const int M = 1e5 + 20; const int mod = 1e9 + 7; const double eps = 1e-6; int cnt, primes[N], mu[N]; bool st[N]; void get(int n) { mu[1] = 1; for (int i = 2; i <= n; i++) { if (!st[i]) { primes[cnt++] = i; mu[i] = -1; } for (int j = 0; primes[j] <= n / i; j++) { st[i * primes[j]] = true; if (i % primes[j] == 0) { mu[i * primes[j]] = 0; break; } mu[i * primes[j]] = -mu[i]; } } for(int i = 2; i <= n; i ++) mu[i] += mu[i - 1]; } int a, b, d; void solve() { sdd(a, b); sd(d); ll ans = 0; a /= d, b /= d; for(int l = 1, r; l <= min(a, b); l = r + 1){ r = min(a / (a / l), b / (b / l)); ans = ans + (ll)(mu[r] - mu[l - 1]) * (a / l) * (b / l); } printf("%lld\n", ans); } int main() { #ifdef ONLINE_JUDGE #else freopen("/home/jungu/code/in.txt", "r", stdin); // freopen("/home/jungu/code/out.txt", "w", stdout); freopen("/home/jungu/code/practice/out.txt","w",stdout); #endif // ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); int T = 1; sd(T); get(100000); // init(); // int cas = 1; while (T--) { // printf("Case #%d:", cas++); solve(); } return 0; }