POJ1742 Coins

题目大意:给定$N$种硬币及其面值$a$和$c$,给定$M$,求$1~M$中有多少种不同的面值可以被这些硬币表示出。

题解

可以用基本的多重背包方法解决。
提供另外一种书上看到的做法:用一个数组表示为了达到某个状态需要的该种硬币的个数,然后利用该数组进行转移,这样就可以不用单调队列而把复杂度降到$O(nm)$。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cmath>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
int n, m, a[105], c[105], used[100005];
bool f[100005];
void init(){
for (int i = 1; i <= n; ++i)
a[i] = read();
for (int i = 1; i <= n; ++i)
c[i] = read();
memset(f, 0, sizeof(f));
}
void solve(){
f[0] = true;
for (int i = 1; i <= n; ++i){
memset(used, 0, sizeof(int) * (m + 1));
for (int j = a[i]; j <= m; ++j){
if(!f[j] && f[j - a[i]] && used[j - a[i]] + 1 <= c[i])
used[j] = used[j - a[i]] + 1, f[j] = true;
}
}
int ans = 0;
for (int i = 1; i <= m; ++i)
if(f[i]) ans++;
printf("%d\n", ans);
}
int main(){
while(n = read(), m = read(), n){
init();
solve();
}
return 0;
}