ACM-ICPC 2016 Qingdao Preliminary Contest G. Sort
Recently, Bob has just learnt a naive sorting algorithm: merge sort. Now, Bob receives a task from Alice.
Alice will give Bob N sorted sequences, and the i-th sequence includes ai elements. Bob need to merge all of these sequences. He can write a program, which can merge no more than k sequences in one time. The cost of a merging operation is the sum of the length of these sequences. Unfortunately, Alice allows this program to use no more than T cost. So Bob wants to know the smallest k to make the program complete in time.
Input
The first line of input contains an integer t0, the number of test cases. t0 test cases follow.
For each test case, the first line consists two integers N (2≤N≤100000) and T (∑Ni=1ai<T<231).
In the next line there are N integers a1,a2,a3,...,aN(∀i,0≤ai≤1000).
For each test case, the first line consists two integers N (2≤N≤100000) and T (∑Ni=1ai<T<231).
In the next line there are N integers a1,a2,a3,...,aN(∀i,0≤ai≤1000).
Output
For each test cases, output the smallest k.
Sample Input
1
5 25
1 2 3 4 5
Sample Output
3
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstdlib> 5 #include <cstring> 6 #include <string> 7 #include <deque> 8 #include <queue> 9 using namespace std; 10 #define ll long long 11 #define N 100009 12 #define gep(i,a,b) for(int i=a;i<=b;i++) 13 #define gepp(i,a,b) for(int i=a;i>=b;i--) 14 #define gep1(i,a,b) for(ll i=a;i<=b;i++) 15 #define gepp1(i,a,b) for(ll i=a;i>=b;i--) 16 #define mem(a,b) memset(a,b,sizeof(a)) 17 int n,m,t; 18 int sum[N],a[N]; 19 priority_queue<int,vector<int>,greater<int> >que; 20 bool check(int k){ 21 while(!que.empty()) que.pop(); 22 int x=(n-1)%(k-1);//共需要归并n-1个数,每次要归并k-1个数 23 int add=0; 24 if(x){//为了不影响单调性 25 x++;//每一次都是减去X个,又加一个。 26 add+=sum[x]; 27 que.push(add);//先去掉x个,后面正常 28 } 29 gep(i,x+1,n) que.push(a[i]); 30 int y=(n-1)/(k-1);//分步骤 31 gep(i,0,y-1){ 32 int tmp=k; 33 int tt=0; 34 while(tmp--){//每次k个 35 int v=que.top(); 36 que.pop(); 37 tt+=v; 38 } 39 que.push(tt);//再压入 40 add+=tt; 41 } 42 return add<=m;//不超过m才行 43 } 44 int main() 45 { 46 scanf("%d",&t); 47 while(t--){ 48 scanf("%d%d",&n,&m); 49 mem(a,0); 50 mem(sum,0); 51 gep(i,1,n) { 52 scanf("%d",&a[i]); 53 } 54 sort(a+1,a+1+n);//要先排序 55 gep(i,1,n){ 56 sum[i]=sum[i-1]+a[i]; 57 } 58 int l=2,r=n;//至少2个 59 while(l<=r){//r可能取到 60 int mid=(r+l)>>1; 61 if(check(mid)) r=mid-1;//r=mid是错的,会死循环 62 else l=mid+1; 63 } 64 printf("%d\n",r+1); 65 } 66 return 0; 67 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现