Coins
Description
People in Silverland use coins.They have coins of value A1,A2,A3...An Silverland dollar.One day Tony opened his money-box and found there were some coins.He decided to buy a very nice watch in a nearby shop. He wanted to pay the exact price(without change) and he known the price would not more than m.But he didn't know the exact price of the watch.
You are to write a program which reads n,m,A1,A2,A3...An and C1,C2,C3...Cn corresponding to the number of Tony's coins of value A1,A2,A3...An then calculate how many prices(form 1 to m) Tony can pay use these coins.
Input
The input contains several test cases. The first line of each test case contains two integers n(1<=n<=100),m(m<=100000).The second line contains 2n integers, denoting A1,A2,A3...An,C1,C2,C3...Cn (1<=Ai<=100000,1<=Ci<=1000). The last test case is followed by two zeros.
Output
For each test case output the answer on a single line.
Sample Input
3 10
1 2 4 2 1 1
2 5
1 4 2 1
0 0
Sample Output
8
4
考察点是《挑战程序设计竞赛》里讲过的多重部分和问题,即"给定一组数,每一组的个数为,求解是否可以选择一些数,使得其和为?
设计状态 为前 个数里选择和恰好为 的数时,第 种数所能留下的最大数量,如果得不到 就是 -1,那么,如果前个元素就可以得到,就没必要去取第件了;否则就只能取目前的第件,那么就至少取一件,问题转化到前件元素加和恰好得到得到的子问题.可以得到状态转移方程:
...
复杂度是
加上滚动数组的写法:
memset(dp,-1,sizeof dp);
dp[0] = 0;
for(int i = 0; i < N; i++){
for(int j = 0; j <= K; j++){
if(dp[j] >= 0)dp[j] = m[i];
else if(j < a[i]||dp[j-a[i]] <= 0)dp[j] = -1;
else dp[j] = dp[j - a[i]] - 1;
}
}
那么这个题,只要按照这个写法把所有小于等于m的数据处理一遍,再遍历看看有多少可以被凑出来就行啦
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MAX_N = 101;
const int MAX_M = 1e5 + 7;
int a[MAX_N], m[MAX_N];
int dp[MAX_M];
int N, M;
int main(){
ios::sync_with_stdio(0);
while(cin>>N>>M){
if(M == 0 && N == 0){
break;
}
for (int i = 0; i < N; i++){
cin >> a[i];
}
for (int i = 0; i < N; i++){
cin >> m[i];
}
memset(dp, -1, sizeof dp);
dp[0] = 0;
for (int i = 0; i < N; i++){
for (int j = 0; j <= M; j++){
if(dp[j]>=0){
dp[j] = m[i];
}else if(j<a[i]||dp[ j - a[i] ]<=0){
dp[j] = -1;
}else{
dp[j] = dp[ j - a[i] ] - 1;
}
}
}
int ans = 0;
for (int i = 1; i <= M; i++){
if(dp[i]>=0){
ans++;
}
}
cout << ans << endl;
}
return 0;
}