Hdu . 5884 sort

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

Solution

  • 我们考虑二分答案 k k k

  • 这就相当于合并石子,但是一次可以选 k k k 个进行合并。

  • 也就是 k k k 叉哈夫曼树,用 O ( n ) O(n) O(n) 方法构造即可(多用一个数组往后推)。

  • 复杂度 O ( n   l o g   n ) O(n\ log\ n) O(n log n)

Code

#include<cstdio>
#include<algorithm>
#include<cctype>
using namespace std;
const int N=1e5+5;
int n,all;
int a[N],b[N];
inline int read()
{
	int X=0,w=0; char ch=0;
	while(!isdigit(ch)) w|=ch=='-',ch=getchar();
	while(isdigit(ch)) X=(X<<1)+(X<<3)+(ch^48),ch=getchar();
	return w?-X:X;
}
inline bool check(int k)
{
	long long sum=0;
	bool first=true;
	int na=0,nb=0,m=0;
	int cnt=k;
	if((n-1)%(k-1)!=0) cnt=(n-1)%(k-1)+1;
	while(n-na+m-nb>1)
	{
		if(!cnt) cnt=k;
		int num=0;
		while(cnt--)
		{
			if(na==n) num+=b[++nb]; else
			if(nb==m) num+=a[++na]; else
				if(a[na+1]<b[nb+1]) num+=a[++na]; else num+=b[++nb];
		}
		sum+=b[++m]=num;
		cnt=0;
	}
	return sum<=all;
}
int main()
{
	int T=read();
	while(T--)
	{
		n=read(),all=read();
		for(int i=1;i<=n;i++) a[i]=read();
		sort(a+1,a+1+n);
		int l=2,r=n,ans=0;
		while(l<=r)
		{
			int mid=l+r>>1;
			if(check(mid))
			{
				r=mid-1;
				ans=mid;
			}else l=mid+1;
		}
		printf("%d\n",ans);
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值