poj 3181 Dollar Dayz 题解(动态规划)

点击打开链接

Dollar Dayz
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 3699   Accepted: 1457

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. Farmer John has exactly $5 to spend. He can buy 5 tools at $1 each or 1 tool at $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
题意:给一个N和K,K表示有价值为1到k的硬币无数个,问选一些硬币让总和为N有多少种方案?

用完全背包的方法再在转移的时候处理一下,可以求出答案,但是结果可能很大要超long long,要用大数。由大数代码可得最大答案不超过33位,可以由两个long long拼接而成代码如下:

#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<vector>
#include<algorithm>
#include<queue>
#include<stack>
#define nn 110
#define inff 0x3fffffff
#define mod 1000000007
#define eps 1e-9
using namespace std;
typedef long long LL;
int n,k;
LL dp[1100];
LL f[1100];
int main()
{
    int i,j;
    LL ix=1;
    for(i=0;i<18;i++)
        ix*=10;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        memset(dp,0,sizeof(dp));
        memset(f,0,sizeof(f));
        dp[0]=1;
        for(i=1;i<=k;i++)
        {
            for(j=0;j<=n;j++)
            {
                if(j-i>=0)
                {
                    f[j]=f[j]+f[j-i]+(dp[j]+dp[j-i])/ix;
                    dp[j]=(dp[j]+dp[j-i])%ix;
                }
            }
        }
        if(f[n]!=0)
        {
            printf("%I64d",f[n]);
            printf("%018I64d\n",dp[n]);
        }
        else
            printf("%I64d\n",dp[n]);
    }
    return 0;
}



你可能感兴趣的:(dp,动态规划,ACM)