CF2267C 题解
albertting
·
·
题解
大家好我来随机写场切题题解了。
思考
首先如果一个值是当前 $x$ 的倍数,那么可以无伤把这个数取干净。
然后如果有一组数都是当前 $x$ 的倍数,那么可以无伤把这一组都给取走。
考虑这组数,设这组数的下标为 $b_1\cdots b_k$,发现 $\gcd\{a_{b_1},a_{b_2},\cdots,a_{b_k},x\}>1$(废话)。
于是考虑找到 $x$ 的所有因子,对于这个因子找出所有 $a$ 中其倍数并求和最终取最大值。单轮时间复杂度 $O(n\sqrt{n})$,非常爆炸。
考虑优化,发现实际上只要取 $x$ 的质因子即可,因为对于一个数 $y=pq$,$y|a_i\Rightarrow p|a_i,q|a_i$,于是取质因子必然是不劣的,于是只需要取出所有质因子即可。通过预处理 SPF 可以做到单轮时间复杂度 $O(n\log n)$,非常良好。
## [Code](https://codeforces.com/contest/2267/submission/392019010)
```cpp
// Author: albertting
// Time: 2026/09/25 22:51:49
#include <bits/stdc++.h>
#define __Made return
#define in 0
#define China__ ;
#define ll long long
#define ld long double
#define lll __int128
#define pb push_back
#define uset unordered_set
#define umap unordered_map
using namespace std;
constexpr int LIM = 3000000;
array<int, LIM + 1> spf;
void sieve() {
iota(spf.begin(), spf.end(), 0);
for(int i = 2; i <= LIM; i++)
if(spf[i] == i)
for(int j = i + i; j <= LIM; j += i)
if(spf[j] > i) spf[j] = i;
}
void solve() {
int n, x;
cin >> n >> x;
map<int, ll> mp;
for(int i = 0; i < n; i++) {
int a; cin >> a;
int b = a;
while(spf[b] > 1) {
int f = spf[b];
mp[f] += a;
while(b % f == 0) b /= f;
}
if(b > 1) mp[b] += a;
}
int b = x;
ll ans = 0;
while(spf[b] > 1) {
int f = spf[b];
ans = max(ans, mp[f]);
while(b % f == 0) b /= f;
}
if(b > 1) ans = max(ans, mp[b]);
cout << ans << '\n';
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0), clog.tie(0);
sieve();
int t; cin >> t;
while(t--) solve();
__Made in China__
}
```