题目
Coins
Time Limit: 3000MS Memory Limit: 30000K
Total Submissions: 49288 Accepted: 16535
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
题目大意
有n种硬币,每种硬币价值ai有ci个,求1~m种可以用这些硬币凑出的钱的个数
题解
初看题目像是多重背包问题,但仔细一看是有一些区别的,本题求的是在1 ~ m中能达到的方案数,起初是想将这n件物品打包变成01背包,然后再用类似dijkstra的算法先求出前k个的解,然后用第k+1个来更新这个解,复杂度O(mnlog(n)),超时了。第二种方法是用dp,st数组记录已经达到的钱,第一层1到n遍历每个背包,然后遍历每个钱(ai ~ m),用st数组更新,需要一个f数组,记录用了多少个硬币,复杂度O(mn)
代码
#include <iostream>
#include <cstring>
using namespace std;
const int M = 1e5 +10, N = 110;
int a[N],c[N],n,m,f[M],ans;
bool st[M];
void init()
{
ans = 0;
memset(st,0, sizeof st);
}
int main()
{
while(scanf("%d%d", &n, &m)&&n)
{
init();
for(int i = 1; i <= n; i ++)
cin >> a[i];
for(int i = 1; i <= n; i ++)
cin >> c[i];
st[0] = true;
for(int i = 1; i <= n; i ++)
{
memset(f,0,sizeof f);
for(int j = a[i]; j <= m; j ++)
if(!st[j]&&st[j-a[i]]&&f[j-a[i]]<c[i])
{
st[j] = true;
f[j] = f[j-a[i]] + 1;
}
}
for(int i = 1; i <= m; i ++)
if(st[i])ans++;
cout << ans << endl;
}
return 0;
}