Ural - Timus - 1009 K-based Numbers 题解2015-02-25Let’s consider
K-based numbers, containing exactly
N digits. We define a number to be valid if its
K-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
Problem Source: USU Championship 1997http://acm.timus.ru/problem.aspx?space=1&num=1009本题题意:1 N代表数字的位数, K代表是以什么为基的,如10进制,2进制的10和22 判断数值是否合法:开头不能为零, 而不能有两个连续的0利用动态规划法,可以很好地解决这个问题。唯一的拐弯处: 要分开处理当前位是0和不是零的情况,所以本程序利用两个数列分别保存这两种情况,最后相加起来就是结果了:
long long calculate(const int n, const int k){int Nze[16] = {0};int Ze[16] = {0};Nze[0] = k - 1;for (int i = 1; i < n; i++){Ze[i] = Nze[i-1];Nze[i] = (Ze[i-1] + Nze[i-1]) * (k-1);}return Nze[n-1] + Ze[n-1];}void K_basedNumbers(){int n = 0, k = 0;cin>>n>>k;cout<<calculate(n, k)<<endl;}int main(){K_basedNumbers();return 0;}
当然也可以使用常量保存结果,不过本题的数值都不大,可以认为是空间效率是O(1)了。没有改进的太大必要。From:csdn博客 靖心