天天看点

UVA 674 Coin Change 钱币兑换问题 类似完全背包

题目:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=114&page=show_problem&problem=615

虽然网上说这是基础题,感觉其实并不简单,虽然有人将此题归为完全背包,但感觉和经典的背包转移还是有些差别。

dp[x][i]表示体积为x时的,前i种物品,能达到的方法种数。

状态转移方程:

dp[x][i]  =dp[x][i-1]+dp[x-cost[i]][i];

意味对于体积为x的背包,若考虑将状态从只用了前

i-1种物品,转移到用了前i种物品。

则要将原来的状态 加上  用了第i种物品时种类数。(其实在x-cost[i]时就已经证明用了第i种物品了)

实际只用一维。

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<climits>
#include<queue>
#include<vector>
#include<map>
#include<sstream>
#include<set>
#include<stack>
#include<cctype>
#include<utility>
#pragma comment(linker, "/STACK:102400000,102400000")
#define PI (4.0*atan(1.0))
#define eps 1e-10
#define sqr(x) ((x)*(x))
#define FOR0(i,n)  for(int i=0 ;i<(n) ;i++)
#define FOR1(i,n)  for(int i=1 ;i<=(n) ;i++)
#define FORD(i,n)  for(int i=(n) ;i>=0 ;i--)
#define  lson   ind<<1,le,mid
#define rson    ind<<1|1,mid+1,ri
#define MID   int mid=(le+ri)>>1
#define zero(x)((x>0? x:-x)<1e-15)
#define mk    make_pair
#define _f     first
#define _s     second
using namespace std;
//const int INF=    ;
typedef long long ll;
//const ll inf =1000000000000000;//1e15;
//ifstream fin("input.txt");
//ofstream fout("output.txt");
//fin.close();
//fout.close();
//freopen("a.in","r",stdin);
//freopen("a.out","w",stdout);
const int INF =0x3f3f3f3f;
const int maxV= 7489    ;
const int n=  5 ;
ll cost[6]={0,50,25,10,5,1};
ll dp[maxV+20];

void work()
{
    memset(dp,0,sizeof dp);
    dp[0]=1;
    for(int i=1;i<=n;i++)
    {
        for(ll v=cost[i];v<=maxV;v++)
        {
            dp[v]+=dp[v-cost[i]];
        }
    }

}

int main()
{
    work();
    int x;
    while(~scanf("%lld",&x))
    {
        printf("%lld\n",dp[x]);
    }

    return 0;
}