Sort
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5241 Accepted Submission(s): 1309
Problem Description
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).
Output
For each test cases, output the smallest k.
Sample Input
1 5 25 1 2 3 4 5
Sample Output
3
Source
2016 ACM/ICPC Asia Regional Qingdao Online
Recommend
wange2014 | We have carefully selected several similar problems for you: 6447 6446 6445 6444 6443
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
queue<int> a;
queue<int> b;
int n,cost;
int num[maxn];
int judge(int k)//calculate the counts in terms of k-banches huffman tree
{
int tepcost=0;
while(!a.empty()) a.pop();
while(!b.empty()) b.pop();
int t=(n-1)%(k-1);
if(t)
for(int i=1;i<=(k-1-t);i++)
a.push(0);
sort(num+1,num+n+1);
for(int i=1;i<=n;i++)
a.push(num[i]);
while(1)
{
if(a.size()==0 && b.size()==1)
break;
int tep=0;
for(int i=1;i<=k;i++)
{
if(!a.empty() && !b.empty())
{
int t1=a.front();
int t2=b.front();
if(t1<t2)
tepcost+=t1,a.pop(),tep+=t1;
else
tepcost+=t2,b.pop(),tep+=t2;
}
else
{
if(!a.empty())
tepcost+=a.front(),tep+=a.front(),a.pop();
else
tepcost+=b.front(),tep+=b.front(),b.pop();
}
}
b.push(tep);
}
return tepcost<=cost;
}
void inti()
{
scanf("%d%d",&n,&cost);
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);
}
int binary_search()
{
int l=2,r=n,mid;
while(l<r)
{
mid=(l+r)/2;
if(judge(mid))
r=mid;
else
l=mid+1;
}
return r;
}
int main()
{
int terms;
scanf("%d",&terms);
for(int i=1;i<=terms;i++)
{
inti();
int ans=binary_search();
printf("%d\n",ans);
}
return 0;
}