洛谷P1255、P2437.
思路相同,注意何时进位以及数组最大长度!
#include <stdio.h> short dp[5020][2000] = { 0 }; void f(int n) { dp[0][0] = 0; dp[1][0] = 1; dp[2][0] = 2; int flag = 0; for (int i = 3; i <= n; i++) { for (int j = 0; j <= flag; j++) { dp[i][j] += dp[i - 1][j] + dp[i - 2][j]; if (dp[i][j] >= 10) { dp[i][j] %= 10; dp[i][j + 1]++; if (j == flag)flag++; } } } for (flag; flag >= 0; flag--) { printf("%d", dp[n][flag]); } } int main() { int n; scanf("%d", &n); f(n); return 0; }
#include <stdio.h> short dp[1010][500] = { 0 }; void f(int m, int n) { int des = 1 + n - m; int flag = 0; dp[1][0] = 0; dp[2][0] = 1; dp[3][0] = 2; for (int i = 4; i <= des; i++) { for (int j = 0; j <= flag; j++) { dp[i][j] += dp[i - 1][j] + dp[i - 2][j]; if (dp[i][j] >= 10) { dp[i][j] %= 10; dp[i][j + 1]++; if (j == flag)flag++; } } } for (flag; flag >= 0; flag--) { printf("%d", dp[des][flag]); } } int main() { int m, n; scanf("%d%d", &m, &n); f(m, n); return 0; }