给你n个数字,每个把k个合并成1个,花费是k个数之和,问你花费不超过T,k最小多少
首先想到二分k去判断,然后就是肯定先合并小的,那么用优先队列
然后T,所以要优化log,想到用单调队列,每次把合并的k个得到的放在单调队列里
后一次合并的,绝对比前一次合并的要大,所以往后放就行了
trick是最后可能不能正好合并k个,所以第一次应该是合并(n−1)
因为要减少n−1个数字,每次减少k−1个,并且+1,如果这个等于1,那么这次操作就不要了
代码:
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#pragma comment(linker,"/STACK:102400000,102400000")
using namespace std;
#define MAX 100005
#define MAXN 1000005
#define maxnode 15
#define sigma_size 30
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define lrt rt<<1
#define rrt rt<<1|1
#define middle int m=(r+l)>>1
#define LL long long
#define ull unsigned long long
#define mem(x,v) memset(x,v,sizeof(x))
#define lowbit(x) (x&-x)
#define pii pair<int,int>
#define bits(a) __builtin_popcount(a)
#define mk make_pair
#define limit 10000
//const int prime = 999983;
const int INF = 0x3f3f3f3f;
const LL INFF = 0x3f3f;
const double pi = acos(-1.0);
const double inf = 1e18;
const double eps = 1e-4;
const LL mod = 1e9+7;
const ull mx = 133333331;
/*****************************************************/
inline void RI(int &x) {
char c;
while((c=getchar())<'0' || c>'9');
x=c-'0';
while((c=getchar())>='0' && c<='9') x=(x<<3)+(x<<1)+c-'0';
}
/*****************************************************/
int a[MAX];
LL q[MAX];
LL T;
int n;
bool check(int x){
int head=0,tail=0;
int tmp=(n-1)%(x-1)+1;
LL ret=0;
LL cost=0;
int tot=0;
if(tmp!=1){
for(int i=0;i<tmp;i++) ret+=a[i];
cost+=ret;
q[tail++]=ret;
tot=tmp;
}
while(!(tot==n&&head+1==tail)){
int k=x;
ret=0;
while(k){
k--;
if(head==tail) ret+=a[tot++];
else{
if(tot==n) ret+=q[head++];
else{
if(a[tot]<=q[head]) ret+=a[tot++];
else ret+=q[head++];
}
}
}
cost+=ret;
q[tail++]=ret;
}
if(cost>T) return false;
return true;
}
int main(){
//freopen("in.txt","r",stdin);
int t;
cin>>t;
while(t--){
scanf("%d%I64d",&n,&T);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
sort(a,a+n);
int l=2,r=n;
while(l<=r){
int mid=(l+r)/2;
if(check(mid)) r=mid-1;
else l=mid+1;
}
cout<<l<<endl;
}
return 0;
}