Ural - Timus - 1009 K-based Numbers 题解

Let’s consider K-based numbers, containing exactly Ndigits. 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 Nand K, you are to calculate an amount of valid Kbased numbers, containing Ndigits.
You may assume that 2 ≤ K≤ 10; N≥ 2; N+ K≤ 18.

Input

The numbers Nand Kin decimal notation separated by the line break.

Output

The result in decimal notation.

Sample

input output
2
10
90
Problem Source:USU Championship 1997
http://acm.timus.ru/problem.aspx?space=1&num=1009
本题题意:
1 N代表数字的位数, K代表是以什么为基的,如10进制,2进制的10和2
2 判断数值是否合法:开头不能为零, 而不能有两个连续的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)了。没有改进的太大必要。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值