Codeforces1003D Coins and Queries

D. Coins and Queries
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Polycarp has nn coins, the value of the ii-th coin is aiai. It is guaranteed that all the values are integer powers of 22 (i.e. ai=2dai=2d for some non-negative integer number dd).

Polycarp wants to know answers on qq queries. The jj-th query is described as integer number bjbj. The answer to the query is the minimum number of coins that is necessary to obtain the value bjbj using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value bjbj, the answer to the jj-th query is -1.

The queries are independent (the answer on the query doesn't affect Polycarp's coins).

Input

The first line of the input contains two integers nn and qq (1n,q21051≤n,q≤2⋅105) — the number of coins and the number of queries.

The second line of the input contains nn integers a1,a2,,ana1,a2,…,an — values of coins (1ai21091≤ai≤2⋅109). It is guaranteed that all aiai are integer powers of 22 (i.e. ai=2dai=2d for some non-negative integer number dd).

The next qq lines contain one integer each. The jj-th line contains one integer bjbj — the value of the jj-th query (1bj1091≤bj≤109).

Output

Print qq integers ansjansj. The jj-th integer must be equal to the answer on the jj-th query. If Polycarp can't obtain the value bjbj the answer to the jj-th query is -1.

Example
input
5 4
2 4 8 2 4
8
5
14
10
output
1
-1
3
2

题意:给你一串由2的整数幂构成的序列(即每个数都是2的整数次方),然后给你一些query,问你最少能用这里的几个数字的和组成当前数字,如果不能组成则输出-1

解法:贪心

因为每个数字都是2的整数幂,所以对于每个给定的数字从大到小贪心,如果可以就用这个数字,直到结束。

由二进制表示一个数可知,任何一个数均能由若干个数(均为2的次幂)的和构成,要想用最少的硬币凑成x,则应该尽量用面值比较大的硬币,所以,从大到小枚举硬币面值。

为什么:想到如果一个b可以被拼出来,那么他就能被写成多个power of 2相加的形式;那么我们每次用最大的power of 2去拼这个b,然后power of 2再逐渐减小,如果能拼的出来的话那他一定是答案;那会不会出现原本拼的出来,但在这种策略下拼不出来的情况呢?(及不应该每次用最大的去拼b)不会,因为如果你能用其他的方式拼出b(而且有更大的power of 2可取但没取),那你一定可以用那些小点的power of 2拼出来这个大的power of 2

#include <bits/stdc++.h>
const int N = 2e5 + 10;
int a[N];
using namespace std;
map<int,int> mp;
int main()
{
    //ios::sync_with_stdio(false);
    //cin.tie(0);
    int n,q;
    //cin >> n >> q;
    scanf("%d%d", &n, &q);
    for(int i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
        mp[a[i]]++;//用map记录每个数字出现的次数
    }
    while(q--)
    {
        int temp;
        scanf("%d", &temp);
        int ans = 0;
        for(int i = 1 << 30; i >= 1; i /= 2)//从最大的数开始向小
        {
            int t = min(temp / i, mp[i]);//选择需要的个数和有的个数的较小数
            ans += t;
            temp -= t * i;
        }
        if(temp)
            puts("-1");//如果temp不等于0则说明不存在
        else printf("%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_37158899/article/details/80969585