题意: 有n个硬币q次询问,每个硬币为2^d, 每次询问给你一个数,问能否用硬币凑成这个数。
思路:因为都是倍数关系,所以有大的用大的,最多就32个不同的数,所以可以桶装,这里用的反向迭代器
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
map<int, int> mp;
int main()
{
int n, q, x, cnt = 0;
scanf("%d%d", &n, &q);
for(int i = 1; i <= n; i++)
{
scanf("%d", &x);
mp[x]++;
}
while(q--)
{
scanf("%d", &x);
int ans = 0, flag = 0;
for(map<int,int>::reverse_iterator it = mp.rbegin(); it != mp.rend(); it++)
{
int tmp = min(x/it->first, it->second);
ans += tmp;
x -= tmp * it->first;
if(!x) break;
}
if(!x) printf("%d\n", ans);
else puts("-1");
}
return 0;
}