K-based Numbers(递推)
http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2062&cid=1157
法一:用dp[i][0]、dp[i][1]表示递推到第i位时为0以及非0的情况种数进行dp。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h> int main() { long long dp[20][2] ; int n, k ; while(scanf("%d %d", &n, &k)!=EOF) { dp[1][1] = k-1 ; dp[1][0] = 0 ; for(int i=2; i<=n; i++) { dp[i][0] = dp[i-1][1] ; dp[i][1] = (k-1)*(dp[i-1][0]+dp[i-1][1]) ; } printf("%lld\n", dp[n][0]+dp[n][1]) ; } return 0 ; }
法二:可以用二进制,即k = 2来模拟,n = 2时,dp = 1; n = 3时, dp= 3 ; n = 4时, dp = 5.....别忘记乘以首位不为零的情况k-1
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<stdio.h> int main() { long long dp[20] ; int n, k ; while(scanf("%d %d", &n, &k)!=EOF) { dp[0] = k-1 ; dp[1] = k*(k-1) ; for(int i=2; i<n; i++) { dp[i] = (k-1)*(dp[i-1]+dp[i-2]) ; } printf("%lld\n", dp[n-1]) ; } return 0 ; }