题解 CF1303D 【Fill The Bag】
首先我们看到
这时我们不妨来观察题目的其他性质。我们注意到,我们只关心我们用现有的或者划分后的物品是否能把背包填满,而并不关心我们用了多少物品。而且题目的物品大小也很有特点:
那么设
再看
想到了这些,无解的情况也就很容易考虑到了。当
于是这题就在这个
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
#define rgt register int
#define qmx(a,b) a<b?b:a
using namespace std;
const int mxn = 1e5+5;
const int mxht = 60;
int m,ans,wht[62],wxn[62],out_n;
ll n,cake[mxn],mxcake,sumcake;
inline ll getcake(){
char c=getchar();
while(c<'0'||c>'9')
c=getchar();
ll inx = (c^48);
c=getchar();
while(c>='0'&&c<='9'){
inx=inx*10+(c^48);
c=getchar();
}
return inx;
} //快速读入
int main(){
int test;
scanf("%d",&test);
while(test--){
n=getcake();
m=getcake();
mxcake=sumcake=out_n=ans=0;
memset(wht,0,sizeof(wht));
for(rgt i=1;i<=m;i++){
cake[i]=getcake();
sumcake+=cake[i];
mxcake=qmx(mxcake,cake[i]);
}//读入数据
if(sumcake<n){
printf("-1\n");
continue;
}//判断无解
sort(cake+1,cake+1+m);
for(rgt iwh=1,cntwh=1,i=1;iwh<=mxcake;iwh<<=1,cntwh++){
while(i<=m&&cake[i]==iwh){
wht[cntwh]++;
i++;
}
}//把每个物品放到对应的桶中
while(n){
out_n++;
wxn[out_n]=(n&1);
n>>=1;
}//求 n 的二进制表示
for(rgt dti,i=1;i<=out_n;i++){
wht[i]+=wht[i-1]/2; //填充上一位的物品两两合并后放到下一位的桶中一起计算
if(wxn[i]){ //当前位是 1,找物品填充。
if(!wht[i]){ //没有物品,去更高位上找物品
dti=i+1;
while(!wht[dti])
dti++;
while(dti>i){
ans++;
wht[dti]--;
wht[dti-1]+=2;
dti--;
} //找到物品,划分,直到回到第 i 位
}
wht[i]--; //用一个物品填上这一位
}
}
printf("%d\n",ans); //得到答案
}
return 0;
}