Description
你有n種硬幣,每種硬幣有c個每個價值a,不同種硬幣價值可能相同,
問你用這些硬幣可以湊出1到m中多少種不同價值
Input
第一行一個整數t表示數據組數,每組數據第一行兩個整數n,m,
接下來n行每行兩個整數表示這種硬幣的a和c
Output
對於每組數據輸出一行可以湊出多少種不同價值
Sample Input
樣例讀入:
2
3 10
1 2
2 1
4 1
2 5
1 2
4 1
樣例輸出:
8
4
HINT
數據範圍:
對於20%的數據,n<=10 a,m<=100 ,c<=10
對於50%的數據,n<=100 a,m<=1000 ,c<=100
對於100%的數據,n<=100 a,m<=100000, c<=1000, t<=3
01揹包. 對c[i]進行二進制拆分優化.
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
const int maxN = 100;
const int maxM = (int)1e5;
int a[maxN];
int c[maxN];
int f[maxM + 1];
int main()
{
#ifndef ONLINE_JUDGE
freopen("coins.in", "r", stdin);
freopen("coins.out", "w", stdout);
#endif
ios::sync_with_stdio(false);
int t;
for(cin >> t; t; t --)
{
int n, m;
cin >> n >> m;
for(int i = 0; i < n; i ++)
cin >> a[i] >> c[i];
memset(f, 0, sizeof(f));
f[0] = 1;
for(int i = 0; i < n; i ++)
{
for(int j = 0; (1 << j) <= c[i]; j ++)
{
c[i] -= (1 << j);
int tmp = a[i] * (1 << j);
for(int k = m; k >= tmp; k --)
if(f[k - tmp])
f[k] = 1;
}
for(int j = m; j >= c[i] * a[i]; j --)
if(f[j - c[i] * a[i]])
f[j] = 1;
}
int ans = 0;
for(int i = 1; i <= m; i ++)
if(f[i])
ans ++;
printf("%d\n", ans);
}
}