题目链接:
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();
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;
}
转载请注明原文地址: https://ju.6miu.com/read-19912.html