Uva 11137 - Ingenuous Cubrency(完全背包)

People in Cubeland use cubic coins. Notonly the unit of currency is called a cube but also the coins are shaped likecubes and their values are cubes. Coins with values of all cubic numbers up to9261(= 213 ), i.e., coins with the denominations of 1, 8, 27, . . ., up to 9261cubes, are available in Cubeland. Your task is to count the number of ways topay a given amount using cubic coins of Cubeland. For example, there are 3 waysto pay 21 cubes: twenty one 1 cube coins, or one 8 cube coin and thirteen 1cube coins, or two 8 cube coin and five 1 cube coins.

 

Input

Input consists of lines each containing aninteger amount to be paid. You may assume that all the amounts are positive andless than 10000.

 

Output

For each of the given amounts to be paidoutput one line containing a single integer representing the number of ways topay the given amount using the coins available in Cubeland.

 

Sample Input

10

21

77

9999

 

Sample Output

2

3

22

440022018293

 

【题意】

   给出一个正整数n,求将n写成若干个正整数的立方数之和有多少种写法?

 【思路】

   类似完全背包问题的动态规划,设dp[i][j]表示用整数1到i的立方和组成数字j的情况数,那么根据完全背包问题的结论dp[i][j]= dp[i-1][j-k*i^3] (k=0,1,2…)对此还可以进一步做优化得dp[i][j] = dp[i-1][j]+dp[i][j-i^3]

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;

const int maxi = 25;//25^3 = 15625已经超过 10000了
const int maxn = 10050;

int n;
ll dp[maxi][maxn];
//dp[i][j]表示用1到i这i个数字的立方和凑出数字j的情况数量
//状态转移方程dp[i][j] = dp[i - 1][j - k*i^3] (k=0,1,2...) 类似完全背包问题的普通解法

int main() {
	memset(dp, 0, sizeof(dp));
	dp[0][0] = 1;
	for (int i = 1; i < maxi; i++) {
		dp[i][0] = 1;
		for (int j = 1; j < maxn; j++) {
			for (int k = 0; j - k*i*i*i >= 0; k++) {
				dp[i][j] += dp[i - 1][j - k*i*i*i];
			}
		}
	}

	while (scanf("%d", &n) == 1) {
		printf("%lld\n", dp[maxi - 1][n]);
	}
	return 0;
}

优化

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxi = 25;
const int maxn = 10050;

int n;
ll dp[maxn];

int main() {
	memset(dp, 0, sizeof(dp));
	dp[0] = 1;
	for (int i = 1; i < maxi; i++) {
		for (int j = i*i*i; j < maxn; j++) {
			dp[j] += dp[j - i*i*i];
		}
	}
	while (scanf("%d", &n) == 1) {
		printf("%lld\n", dp[n]);
	}
	return 0;
}


posted @ 2017-11-20 23:08  不想吃WA的咸鱼  阅读(174)  评论(0编辑  收藏  举报