CodeForces - 1303D Fill the bag

CodeForces - 1303D Fill the bag

题解:二进制+思维

首先我们发现这肯定与二进制有关,n的二进制形式肯定有1,所以我们去从低位到高位遍历n的二进制的时候,加入现在这一位是1,那我们肯定想要知道现在有没有这么大的盒子,如果没有这么大的盒子,那我们需要拆更大的盒子,所以我们必须记录相应盒子大小的数量,但是很显然元素a的范围太大了,所以\(cnt[i]\)的意思就是\(2^i\)大小盒子的数量,但是这只是完成了一半,我们来看一个样例

\(n=10,a=[1,1,32]\),所以我们来看一下10的二进制:1010,显然当我们遍历第一个1的时候,我们发现cnt[1]=0,没有对应大小的盒子。所以我们必须拆大盒子,\(32->16->8->4->2\),一共拆了四次,并且cnt[4]=cnt[3]=cnt[2]=1,这样的话总共的分解次数为4,但是我们发现还有更优的,就是把两个1凑成2,这说明什么我们可以把小盒子合成大盒子,所以当我们遍历完第一位0后,就把\(cnt[1]+=cnt[0]/2\),这样就算是合成大盒子了

#include <bits/stdc++.h>
#define Zeoy std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0)
#define all(x) (x).begin(), (x).end()
#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-9;
const int N = 1e5 + 10;
int lowbit(ll x)
{
    int ans = 0;
    while (x)
    {
        x >>= 1;
        ans++;
    }
    return ans;
}
ll cnt[100];
int main(void)
{
    Zeoy;
    int t = 1;
    cin >> t;
    while (t--)
    {
        ll n, m;
        cin >> n >> m;
        memset(cnt, 0, sizeof cnt);
        for (int i = 1; i <= m; ++i)
        {
            ll x;
            cin >> x;
            cnt[lowbit(x)]++;
        }
        ll ans = 0;
        int flag = 1;
        for (int i = 1; i <= 64 && n; ++i)
        {
            if (n & 1)					
            {
                if (cnt[i] > 0)				//当前有一样大的盒子
                    cnt[i]--;
                else
                {
                    int j = i;
                    while (j <= 64 && !cnt[j])
                    {
                        cnt[j]++;
                        ans++;
                        j++;
                    }
                    if (j != 65)
                        cnt[j]--;
                    else
                    {
                        flag = 0;
                        break;
                    }
                }
            }
            cnt[i + 1] += cnt[i] / 2;		//合并小盒子
            n >>= 1;
        }
        if (flag)
            cout << ans << endl;
        else
            cout << "-1" << endl;
    }
    return 0;
}
posted @ 2023-01-08 18:05  Zeoy_kkk  阅读(15)  评论(0编辑  收藏  举报