题意:n位数,k进制,求个数
分析:dp[i][j] 表示i位数,当前数字为j的个数;若j==0,不加dp[i-1][0];
代码1:
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> using namespace std; const int MAXN = 22; const int INF = 0x3f3f3f3f; long long dp[MAXN][MAXN]; int main(void) //URAL 1009 K-based Numbers { //freopen ("B.in", "r", stdin); int n, k; while (scanf ("%d%d", &n, &k) == 2) { memset (dp, 0, sizeof (dp)); for (int i=1; i<k; ++i) dp[1][i] = 1; for (int i=2; i<=n; ++i) { for (int j=0; j<k; ++j) { if (!j) for (int l=1; l<k; ++l) dp[i][j] += dp[i-1][l]; else for (int l=0; l<k; ++l) dp[i][j] += dp[i-1][l]; } } long long ans = 0; for (int i=0; i<k; ++i) ans += dp[n][i]; printf ("%I64d ", ans); } return 0; }
代码2(空间优化):
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> using namespace std; const int MAXN = 22; const int INF = 0x3f3f3f3f; long long dp[MAXN]; int main(void) //URAL 1009 K-based Numbers { //freopen ("B.in", "r", stdin); int n, k; while (scanf ("%d%d", &n, &k) == 2) { memset (dp, 0, sizeof (dp)); dp[0] = 1; dp[1] = k - 1; for (int i=2; i<=n; ++i) { dp[i] = (dp[i-1] + dp[i-2]) * (k-1); } printf ("%I64d ", dp[n]); } return 0; }