Acm VF

VF

時間限制:1000 ms  |  內存限制:65535 KB
難度:2
描述
Vasya is the beginning mathematician. He decided to make an important contribution to the science and to become famous all over the world. But how can he do that if the most interesting facts such as Pythagor’s theorem are already proved? Correct! He is to think out something his own, original. So he thought out the Theory of Vasya’s Functions. Vasya’s Functions (VF) are rather simple: the value of the Nth VF in the point S is an amount of integers from 1 to N that have the sum of digits S. You seem to be great programmers, so Vasya gave you a task to find the milliard VF value (i.e. the VF with N = 109) because Vasya himself won’t cope with the task. Can you solve the problem?
輸入
There are multiple test cases.
Integer S (1 ≤ S ≤ 81).
輸出
The milliard VF value in the point S.
樣例輸入
1
樣例輸出
10
來源
USU Junior Championship March'2005
上傳者

李文鑫


題意:1~1000000000之間,各位數字之和等於給定s的數的個數。

每行給出一個數s(1 ≤ s ≤ 81),求出1~10^9內各位數之和與s相等的數的個數。


思路:可以將本問題若干子問題,即給出一個數s,分別求出 i(1<=i<=10)位數滿足各位數和等於s的情況,創建數組data[i][j],i=10,1<=j<=81(給出的最大s值爲81,即每一位上面的數都爲9)。

當s=1時,總個數爲10。每位數上面分別爲1時。

當s!=1時,初始化數組data[i][j];,i對應的是i(1<=i<=10)位數,j對應的可能給出的s。所以我們只需要將數組填滿,最後的個數sum+=data[i][s]個。

例如我們給出的s等於5:

1、只有一位數的時候只有1種,5

2、有兩位數的時候有5種,14,23,32,41,50

3、有三位數的時候有15種

4、有四位數的時候有.....

.........

10、有十位數的時候有:495種

所以總個數爲sum= 1 + 5+.....+495種

那麼爲題來了,我們怎麼才能知道data[i][j]對應的次數呢。

例如:我們把問題縮小化,我們想知道data[4][5]的次數,即1-10^4內各位數之和與5相等的數的個數.

第一步:求得千位數爲1,2,3,4,5時滿足的情況

1、當千位數爲1時,百位數爲4(即1-10^3內各位數之和與4相等的數的個數),百位數爲4滿足的情況(當百位數爲1時,十位數爲3即1-10^3內各位數之和與3相等的數的個數)........

2、當千位數爲2時,百位數爲3(即1-10^3內各位數之和與3相等的數的個數),百位數爲3滿足的情況(當百位數爲1時,十位數爲2即1-10^3內各位數之和與2相等的數的個數)........

.......

最後總結得:data[i][j] += data[i][k](1<=i<=10)  (1 <= k <=9*i)     ,


import java.io.BufferedInputStream;
import java.util.Scanner;

public class _269_2_AC_DP {
	public static void main(String[] args) {

		Scanner scan = new Scanner(new BufferedInputStream(System.in));
		int testData, sum = 0;
		int[][] data = new int[10][82];
		for (int i = 1; i < 10; ++i) {
			data[1][i] = 1;
		}
		for (int i = 1; i < 10; ++i) {
			for (int j = 1; j <= i * 9; ++j) {
				for (int k = 0; k <= 9 && k <= j; ++k) {
					data[i][j] += data[i - 1][j - k];
				}
			}
		}
		while (scan.hasNext()) {
			testData = scan.nextInt();
			if (testData == 1) {
				System.out.println(10);
			} else {
				for (int i = 1; i < 10; ++i) {
					sum += data[i][testData];
				}
				System.out.println(sum);
				sum = 0;
			}
		}

	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章