1. 程式人生 > 實用技巧 >Acwing 200 Hankson的趣味題

Acwing 200 Hankson的趣味題

題意:

給定$a, b, c, d$,求$x$滿足$gcd(a, x) = b$且$lcm(c, x) = d$

思路:

列舉d的所有約數,判斷每個數是否滿足條件。(直接列舉會超時)

優化:列舉質數(相當於d質因子分解),$dfs$列舉所有約數,判斷是否滿足條件

Code:

#include <map>
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace
std; typedef long long ll; ll a, b, c, d, x; vector <pair<int, int>> v; map <ll, bool> mp; void dfs(int cnt, ll res){ if(!mp[res] && __gcd(a, res)== b && c / __gcd(c, res) * res == d){ x ++; mp[res] = true; } if(cnt == (int)v.size()) return
; int p = v[cnt].first, k = v[cnt].second; ll mid = 1; for(int i = 0; i <= k; i ++){ dfs(cnt + 1, res * mid); mid *= p; } } int main(){ int n; scanf("%d", &n); while(n --){ x = 0; scanf("%lld%lld%lld%lld", &a, &b, &c, &d); v.clear(); mp.clear(); ll k
= d; for(int i = 2; i <= k / i; i ++){ if(k % i == 0){ int s = 0; while(k % i == 0){ s ++; k /= i; } v.push_back({i, s}); } } if(k > 1) v.push_back({k, 1}); dfs(0, 1); cout << x << endl; } return 0; }