[USACO 20OPEN] Exercise G(素数 DP) | 错题本
题目
分析
问题就是求 K K K 的和,使得存在 { a i } \{a_i\} {ai} 满足 lcm a i = K , ∑ a i = N \text{lcm}\ a_i = K, \sum a_i = N lcm ai=K,∑ai=N,将所有 a i a_i ai 分解质因数后 K K K 就是它们质因数对应最高次数的乘积。考虑枚举 K K K 各个质因数的以及它们的幂,其之和不会超过 N N N,通过算贡献的方法进行背包即可。
代码
#include <bits/stdc++.h>
int Read() {
int x = 0; bool f = false; char c = getchar();
while (c < '0' || c > '9')
f |= c == '-', c = getchar();
while (c >= '0' && c <= '9')
x = x * 10 + (c ^ 48), c = getchar();
return f ? -x : x;
}
typedef long long LL;
const int MAXN = 10000;
int N, M;
bool Vis[MAXN + 5];
int Pri[MAXN + 5], Cnt;
void Init(const int &n) {
for (int i = 2; i <= n; i++) {
if (!Vis[i])
Pri[++Cnt] = i;
for (int j = 1; j <= Cnt && i * Pri[j] <= n; j++) {
Vis[i * Pri[j]] = true;
if (i % Pri[j] == 0)
break;
}
}
}
LL Dp[MAXN + 5];
int main() {
N = Read(), M = Read();
Init(N);
Dp[0] = 1;
for (int i = 1; i <= Cnt; i++) {
for (int j = N; j >= Pri[i]; j--) {
int cur = Pri[i];
while (cur <= j)
Dp[j] = (Dp[j] + Dp[j - cur] * cur % M) % M, cur *= Pri[i];
}
}
LL Ans = 0;
for (int i = 0; i <= N; i++)
Ans = (Ans + Dp[i]) % M;
printf("%lld", Ans);
return 0;
}
本文地址:https://blog.csdn.net/C20190102/article/details/110170772