【題解】Codeforces 1303D. Fill The Bag

【題目敘述】http://codeforces.com/contest/1303/problem/D

#include <iostream>
#include <map>
#include <cstring>
using namespace std;
 
int t, m, cnt[65];
long long n, a, total, ans;
map <int, int> mp;
 
int main() {
    cin >> t;
    for (int i = 0; i < 60; i++){
        mp[(1LL << i)] = i;
    }
    while (t--){
        cin >> n >> m;
        total = 0;
        memset(cnt, 0, sizeof(cnt));
        for (int i = 0; i < m; i++){
            cin >> a;
            total += a;
            cnt[mp[a]]++;
        }
        if (total < n){
            cout << -1 << "\n";
            continue;
        }
        ans = 0;
        for (int i = 0; i < 61; i++){
            if (n & (1LL<<i)){
                for (int j = i; j <= 60; j++){
                    if (cnt[j]){
                        ans += j-i;
                        cnt[j]--;
                        for (int k = j-1; k >= i; k--){
                            cnt[k]++;
                        }
                        break;
                    }
                }
            }
            cnt[i+1] += cnt[i]/2;
        }
        cout << ans << "\n";
    }
}
分享本文 Share with friends