题目
分析
考虑统计二进制含 j j j 个 1 1 1 的数有多少个,于是设计 d p [ i ] [ j ] [ 0 / 1 ] dp[i][j][0/1] dp[i][j][0/1] 表示前 i i i 位中出现了 j j j 个 1 1 1,且前 i i i 位比 n n n 小 / / / 和 n n n 相等的数个数,转移刷表,分填 0 0 0 和填 1 1 1 即可。本题可以算个板子。
错因
- DP 的时候不要取模。
md 指数当然不能取模
代码
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
typedef long long LL;
const int MOD = 10000007;
const int MAXL = 50;
inline int Add(int x, const int &y) {
return (x += y) >= MOD ? x - MOD : x;
}
inline int Mul(const int &x, const int &y) {
return (LL)x * y % MOD;
}
int Pow(int x, LL y) {
int ret = 1;
while (y) {
if (y & 1)
ret = Mul(ret, x);
y >>= 1;
x = Mul(x, x);
}
return ret;
}
LL N;
int R[MAXL + 5], len;
LL Dp[MAXL + 5][MAXL + 5][2];
int main() {
scanf("%lld", &N);
int Ans = 0;
while (N) {
Ans += (R[len++] = N & 1);
N >>= 1;
}
Dp[0][0][1] = 1;
for (int i = 0; i < len; i++) {
int r = R[len - i - 1];
for (int j = 0; j <= i; j++)
for (int k = 0; k <= 1; k++)
if (Dp[i][j][k]) {
Dp[i + 1][j][k && !r] += Dp[i][j][k]; // 填 0
if (!k || r) Dp[i + 1][j + 1][k && r] += Dp[i][j][k]; // 填 1
}
}
for (int i = 1; i <= len; i++)
Ans = Mul(Ans, Pow(i, Dp[len][i][0]));
printf("%d", Ans);
return 0;
}
洛谷4317数论题DP解法

本文详细解析洛谷4317题花神的数论题,采用动态规划策略,设计状态表示前i位中出现j个1的数,对比给定数n的大小关系,避免取模错误,最终通过指数运算得出答案。
9277

被折叠的 条评论
为什么被折叠?



