1303D 1900
题意:给你一个数n和长度为m的数组,同时这m个数保证都是2的幂次方,问你是否可以通过对m中的数除2的操作,然后相加得到m,如果能打印最小的操作数,如果不能打印-1
思路:从题目中2的幂次方可以联想到这是一个和位运算有关的题目,如果分别把n和m中的数变成二进制来计算,从低位到高位,如果m中的数在二进制,该位为0,而n为1,那么就意味着,m中这个位要向前面的取一,即a[pos]–,而为什么是从低位到高位,而不是高位到低位,因为我们的低位是首先要满足的,而你要最优的操作数,如果从最高位开始,不知道是怎么计算,综上,代码也就可以出来了,当然还有一个从一开始就要判断的如果这m个数的和是小于n的话就不可能变成n,但如果是大于等于n的话就一定可以变成n。
#pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define int ll
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 1e5+10;
inline int read(){
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=(x<<3)+(x<<1)+ch-48;ch=getchar();}
return x*f;
}
inline void cf(){
int t = read();
while(t--){
int n=read(), m=read(), a[65], sum = 0;
memset(a,0,sizeof(a));
rep(i,1,m){
int x = read(), j = 0;
sum += x;
while(x>>j) j++;
a[j-1]++;
}
if(n>sum) {printf("-1\n");continue;}
int ans = 0, pos = 0;
while(n||a[pos]<0){
int tmp = n%2;n/=2;
a[pos]-=tmp;
if(a[pos]>=0) a[pos+1] += a[pos]/2;
else a[pos+1]--, ans++;
pos++;
}
printf("%lld\n", ans);
}
return ;
}
signed main(){
cf();
return 0;
}