Dollar Dayz
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 6735 Accepted: 2523
Description
Farmer John goes to Dollar Days at The Cow Store and discovers an unlimited number of tools on sale. During his first visit, the tools are selling variously for 1, 2, and 3.FarmerJohnhasexactly 5 to spend. He can buy 5 tools at 1eachor1toolat 3 and an additional 1 tool at $2. Of course, there are other combinations for a total of 5 different ways FJ can spend all his money on tools. Here they are:
1 @ US$3 + 1 @ US$2
1 @ US$3 + 2 @ US$1
1 @ US$2 + 3 @ US$1
2 @ US$2 + 1 @ US$1
5 @ US$1
Write a program than will compute the number of ways FJ can spend N dollars (1 <= N <= 1000) at The Cow Store for tools on sale with a cost of
1..
K (1 <= K <= 100).
Input
A single line with two space-separated integers: N and K.
Output
A single line with a single integer that is the number of unique ways FJ can spend his money.
Sample Input
5 3
Sample Output
5
//这一题的递推公式还是比较好找的,因为前后的状态间关系很明显,设dp[i][j]为用从1到i种数组合成j的种数的和,则有
if (j < w[i]){
dp[i][j] = dp[i-1][j];
}
else{
dp[i][j] = dp[i-1][j] + dp[i][j-w[i]];
}
但是输入1000,100时,会发现数据溢出了,即使用long long也会溢出,这里就需要借助到对大数的处理。首先,看下各数据范围:
unsigned int 0~4294967295
int 2147483648~2147483647
unsigned long 0~4294967295
long 2147483648~2147483647
long long的最大值:9223372036854775807
long long的最小值:-9223372036854775808
unsigned long long的最大值:1844674407370955161
__int64的最大值:9223372036854775807
__int64的最小值:-9223372036854775808
unsigned __int64的最大值:18446744073709551615
显然long long只有前18位可以每一位从0到9全部去到,因此我们在这里把最终的种数分为两部分,用两个数组表示,第一个数组表示后18位,第二个数组表示前18位,最后依次输出。
/*
* Filename: code.cpp
* Created: 2017-02-10
* Author: wyl6
*[mail:17744454343@163.com]
* Desciption: Desciption
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <bitset>
#include <list>
#include <sstream>
#include <set>
#include <functional>
using namespace std;
#define INT_MAX 1 << 30
#define MAX 100
typedef long long ll;
int n,k;
int w[101];
long long dpfront[101][1001];
long long dpbehind[101][1001];
long long m = 1;
int main(int argc, char const* argv[])
{
scanf("%d%d",&n,&k);
for (int i = 1; i <= k; i += 1) w[i] = i; //从小到大,第i个数所占容量为i
memset(dpbehind,0,sizeof(dpbehind));
memset(dpfront,0,sizeof(dpfront));
for (int i = 0; i <= k; i += 1) dpbehind[i][0] = 1; //前i种数合成和为0的可能种数只有一个
for (int i = 0; i < 18; i += 1) m *= 10;
for (int i = 1; i <= k; i += 1){
for (int j = 1; j <= n; j += 1){
if (j < w[i]){
dp[i][j] = dp[i-1][j];
}
else{
dp[i][j] = dp[i-1][j] + dp[i][j-w[i]];
}
}
}
if (dpfront[k][n] > 0) printf("%lld",dpfront[k][n]);//输出前18位
printf("%lld\n",dpbehind[k][n]); //输出后18位
return 0;
}