SDUT2062 K-based Numbers(递推)
分析:
这题很水,只是做的时候对边界没有分析正确,WA了很多次。发上来,警示自己要细心。
方法1:
设f(n)为第n为可以为0的排法:
View Code
#include <stdio.h> #include <stdlib.h> #include <string.h> int dp[100], k; int f(int n){ if(n == 1) return k; if(n == 2) return (k-1)*(k+1); else if(dp[n]) return dp[n]; else return (dp[n] = (k-1)*(f(n-1)+f(n-2))); } int main(){ int n; while(scanf("%d %d", &n, &k) == 2){ memset(dp, 0, sizeof(dp)); dp[n] = (k-1)*f(n-1); printf("%d\n", dp[n]); } return 0; }
方法2:
设f(n)为第n为不为0的排法.
View Code
#include <stdio.h> #include <stdlib.h> #include <string.h> int dp[100], k; int f(int n){ if(n == 1) return k-1; if(n == 2) return k*(k-1); else if(dp[n]) return dp[n]; else return (dp[n] = (k-1)*(f(n-1)+f(n-2))); } int main(){ int n; while(scanf("%d %d", &n, &k) == 2){ memset(dp, 0, sizeof(dp)); dp[n] = f(n); printf("%d\n", dp[n]); } return 0; }