您的位置:首页 > 其它

Ural - Timus - 1009 K-based Numbers 题解

2014-04-17 15:06 423 查看
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

inputoutput
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)了。没有改进的太大必要。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: