挑战练习题2.3动态规划 poj1742 Coins 多重背包

题目链接:

http://poj.org/problem?id=1742

题意:

有n种面额的硬币,面额个数分别为A_i、C_i,求最多能搭配出几种不超过m的金额?

题解:

多重部分和问题。多重背包优化? O(n^2)
dp[i][j] := 用前i种硬币凑成j时第i种硬币最多能剩余多少个(-1表示配不出来)
1.如果dp[i - 1][j] >= 0(前i-1个数可以凑出j,那么第i个数根本用不着)直接为C[i]
2.如果j < A[i]或者dp[i][j - a[i]] <=0 (面额太大或者在配更小的数的时候就用光了)就为-1
3.其他(将第i个数用掉一个) dp[i][j-a[i]] - 1

会MLE,要滚动优化

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;

int a[maxn],c[maxn],dp[2][maxn];

int main(){
    int n,m;
    while(scanf("%d%d",&n,&m)==2 && (n+m)){
        for(int i=1; i<=n; i++)
            a[i] = read();
        for(int i=1; i<=n; i++)
            c[i] = read();

// dp[i][j] := 用前i种硬币凑成j时第i种硬币最多能剩余多少个(-1表示配不出来)
//     如果dp[i - 1][j] >= 0(前i-1个数可以凑出j,那么第i个数根本用不着)直接为C[i]
// dp[i][j] =  如果j < A[i]或者dp[i][j - a[i]] <=0 (面额太大或者在配更小的数的时候就用光了)-1
//     其他(将第i个数用掉一个) dp[i][j-a[i]] - 1

        int now=0,pre=1;
        memset(dp,-1,sizeof(dp));
        dp[now][0] = 0;
        for(int i=1; i<=n; i++){
            swap(now,pre);
            for(int j=0; j<=m; j++){
                if(dp[pre][j] >= 0)
                    dp[now][j] = c[i];
                else if(j<a[i] || dp[now][j-a[i]]<=0)
                    dp[now][j] = -1;
                else
                    dp[now][j] = dp[now][j-a[i]]-1;
            }
        }

        int ans = 0;
        for(int i=1; i<=m; i++)
            if(dp[now][i]>=0)
                ans++;

        cout << ans << endl;
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值