Educational Codeforces Round 82 (Rated for Div. 2)D. Fill The Bag

D. Fill The Bag
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You have a bag of size n. Also you have m boxes. The size of i-th box is ai, where each ai is an integer non-negative power of two.

You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.

For example, if n=10 and a=[1,1,32] then you have to divide the box of size 32 into two parts of size 16, and then divide the box of size 16. So you can fill the bag with boxes of size 1, 1 and 8.

Calculate the minimum number of divisions required to fill the bag of size n.

Input
The first line contains one integer t (1≤t≤1000) — the number of test cases.

The first line of each test case contains two integers n and m (1≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.

The second line of each test case contains m integers a1,a2,…,am (1≤ai≤109) — the sizes of boxes. It is guaranteed that each ai is a power of two.

It is also guaranteed that sum of all m over all test cases does not exceed 105.

Output
For each test case print one integer — the minimum number of divisions required to fill the bag of size n (or −1, if it is impossible).

Example
inputCopy
3
10 3
1 32 1
23 4
16 1 4 1
20 5
2 1 16 1 8
outputCopy
2
-1
0

题意:就是给了一个数字n,然后给了m个数,这m个数都是2的幂次方
现在每次操作你可以把m个数中的一个一分为2,比如32 操作一次得到两个16,在操作一次就是4个8,
这样是操作了两次,现在问你 最少要操作多少次,可以在操作后把这些数字恰好凑为n

思路:显然 如果m个数总和<n 自然就是输出-1
如果可以的话我们考虑二进制,先把这m个数,用cnt[i]存下来 cnt[i]表示二进制从低到高 第i位有多少个数
然后 我们对于n进二进制,
如果对于n当前该二进制位i是1.,我们去看cnt[i]是不是有没有,有的话,自然就不用把其他数拆分为两个原来的一半,然后如果该为有剩余,每两个可以凑成一个cnt[i+1]
如果cnt[i]为0,我们就ans++,然后cnt[i+1]–,因为我们需要实现一个拆分
所以最后答案就是ans 也就是拆分的次数

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll cnt[70];
int main()
{
    int t;cin>>t;
    while(t--)
    {
      memset(cnt,0,sizeof cnt);
      ll n,m;
      cin>>n>>m;
      ll sum=0;
      for(int i=0;i<m;i++){

          int num=0,x;
          cin>>x;
          sum+=x;
          while(x) num++,x>>=1;
          cnt[num-1]++;

      }
      if(sum<n) {puts("-1");continue;}
      else
      {
          int ans=0;
          for(int i=0;i<=63;i++){

             int x=(n>>i)&1;
             cnt[i]-=x;
             if(cnt[i]>=2) cnt[i+1]+=cnt[i]/2;
             if(cnt[i]<0) ans++,cnt[i+1]--;
          }
          cout<<ans<<endl;
      }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我不会c语言

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值