ural 1009. K-based Numbers
Let’s consider K-based numbers, containing exactly N digits. We define a number to be valid if itsK-based notation doesn’t contain two successive zeros. For example:
- 1010230 is a valid 7-digit number;
- 1000198 is not a valid number;
- 0001235 is not a 7-digit number, it is a 4-digit number.
Given two numbers N and K, you are to calculate an amount of valid K based numbers, containing Ndigits.
You may assume that 2 ≤ K ≤ 10; N ≥ 2; N + K ≤ 18.
Input
The numbers N and K in decimal notation separated by the line break.
Output
The result in decimal notation.
Sample
input | output |
---|---|
2
10
|
90
|
Problem Source: USU Championship 1997
题意:比较简单的动态规划,题意是说一个K进制数,有N位,开头不能是0,中间不能有两个以上相邻的0
问:求出n位的k进制数有多少个;
思路:
建立一个二维的数组dp[2][20];令dp[1][1]=k-1;
然后有两个递归方程;(1).dp[0][i]=dp[1][i-1];表示从最高位起的第i位是0的前i位组成的数有多少种;dp[1][i]=(dp[0][i-1]+dp[1][i-1])*(k-1);表示从最高位起的第i位是非0数的前i位组成的数有多少种;
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 4 using namespace std; 5 6 int main() 7 { 8 int dp[2][20]; 9 int n,k; 10 cin>>n>>k; 11 int i,j; 12 for(i=0;i<=1;i++) 13 for(j=0;j<=k;j++) 14 dp[i][j]=0; 15 dp[1][1]=k-1; 16 for(i=2;i<=n;i++) 17 { 18 dp[0][i]=dp[1][i-1]; 19 dp[1][i]=(k-1)*(dp[0][i-1]+dp[1][i-1]); 20 } 21 cout<<dp[0][n]+dp[1][n]<<endl; 22 return 0; 23 }