Problem B | Boxes of Chocolates Again |
Time Limit | 4 Seconds |
Little Pippy has got again a big bunch of boxes of chocolates on her 7th birthday. Her parents are anxious about the health of her teeth, so they have allowed her to take only a limited number of chocolates; lets call this number N. They know that Pippy always shares her belongings with her friends, so they have fixed a sufficiently large number to make sure that all are happy. The chocolates are packed in several types of boxes. Each type of box contains a certain number of chocolates which is written above the box. Boxes of different types contain different numbers of chocolates. If a box contains k chocolate(s) we will call it type-k box. Now Pippy should take exactly N chocolates without tearing apart any box. Your job is to determine in how many ways Pippy can do this. You may assume that there are infinitely many boxes of each type fromtype-1 to type-N.
For example, lets assume that Pippy has been asked to take 3 chocolates. She can take only one type-3 box or she can take one type-2 box and one type-1 box or she can take 3 type-1 boxes.
Input
There will be several lines as input each containing a candidate N as described above. N can be any nonnegative number less than or equal to5000. It may look like that N is very big for a little 7 year old girl; but remember she has lots of friends. And, who knows, may be you are one of her friends!
Output
For each N, print an integer on a single line indicating the number of ways Pippy can take N chocolates.
Sample Input | Output for Sample Input |
3 4 5 | 3 5 7 |
Problemsetter: Tanveer Ahsan
International Islamic University Chittagong
分析:DP
5=1+1+1+1+1
5=1+1+1+2
5=1+2+2
5=1+1+3
5=2+3
5=1+4
5=5
现在从小到大排序拆分的数。
用dp[i][j]表示将i拆成若干个数字,最大的那个数字(即最后一个数)不超过j的方案数。
So:dp[i][j] = dp[i][j-1] + dp[i-j][j]
最后的dp[N][N]即为答案。时间复杂度O(N^2)。
PS:Need高精度!
感觉复杂度略高!寻求更精简的方法~
//UVa-10590-Boxes of Chocolates Again——DP + 高精度
#include<iostream>
#include<string>
using namespace std;
class BigInt
{
public:
int a[1000];
int len;
void print();
BigInt()
{
len = 0;
memset(a, 0, sizeof(a));
}
BigInt operator + (BigInt &b) const;
};
void BigInt::print()
{
int tag = 1;
if(len == 0) printf("0");
else
{
for(int i=len-1;i>=0;i--)
{
if(tag) printf("%d",a[i]);
else printf("%.9d",a[i]);
tag = 0;
}
}
}
BigInt BigInt::operator + (BigInt &b) const
{
int max = len>b.len ? len : b.len;
BigInt c; // c = a + b
int carry = 0; // 进位
for(int i=0;i<max+1;i++)
{
long long sum = a[i]+b.a[i]+carry;
carry = 0;
if(sum < 1000000000) c.a[i] = sum;
else
{
c.a[i] = sum % 1000000000;
carry = sum / 1000000000;
}
}
int j = max+2;
while(j--)
{
if(c.a[j] != 0) break;
}
c.len = j+1;
return c;
}
BigInt dp[5010];
int main()
{
int n;
dp[0].a[0] = 1;
dp[0].len = 1;
for(int i=1;i<=1000;i++) // 5000太慢了...
for(int j=i;j<=1000;j++)
dp[j] = dp[j] + dp[j-i];
while(scanf("%d",&n) != EOF)
{
dp[n].print();
printf("\n");
}
return 0;
}