【HDU - 5884】Sort(二分+数组模拟优先队列)

Recently, Bob has just learnt a naive sorting algorithm: merge sort. Now, Bob receives a task from Alice. 
Alice will give Bob NN sorted sequences, and the ii-th sequence includes aiai elements. Bob need to merge all of these sequences. He can write a program, which can merge no more than kk 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 TT cost. So Bob wants to know the smallest kk to make the program complete in time.

Input

The first line of input contains an integer t0t0, the number of test cases. t0t0 test cases follow. 
For each test case, the first line consists two integers N (2≤N≤100000)N (2≤N≤100000) and T (∑Ni=1ai<T<231)T (∑i=1Nai<T<231). 
In the next line there are NN integers a1,a2,a3,...,aN(∀i,0≤ai≤1000)a1,a2,a3,...,aN(∀i,0≤ai≤1000).

Output

For each test cases, output the smallest kk.

Sample Input

1
5 25
1 2 3 4 5

Sample Output

3

题意:

给n个序列每个序列长度为ai,求最少每次合并多少个序列,能使得合并的总花费小于等于T,一次合并的花费是合并的所有序列的长度和。

思路:

合并的时候按照哈夫曼树的合并思想,先合并小的,不过前面需要补0,因为合并到最后可能剩下一部分不到K个,那么剩下的数量在最开始合并会比在最后合并要好。然后这道题通过二分找k值,然后通过数组模拟优先队列来实现。这里如果用优先队列会有个log这样会T,因此可以通过数组模拟来去掉log。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<vector>
#define mod (1000000007)
using namespace std;
typedef long long ll;
int a[200010];
int c[200010];
int b[200010];
int T;
//数组模拟队列
int cal(int n,int k){
	int i=1;
	int b1=0,cnt=0;
	int x=0;
	int ans=0;
	int add=0,y=k;
	if(k!=2)
	while((n+add)%(k-1)!=1){
		add++;
	}
	for(int j=n;j>=1;j--)
	c[j+add]=a[j];
	for(int j=add;j>=1;j--)
	c[j]=0;
	n+=add;
	while(true){
		int x=0;
		int ad=0;
		while((i<=n||b1<cnt)&&x<k){
			if(i>n){
				ad+=b[b1];
				ans+=b[b1];
				b1++;
			}
			else if(b1>=cnt){
				ad+=c[i];
				ans+=c[i];
				i++;
			}
			else{
				if(c[i]<b[b1]){
					ad+=c[i];
					ans+=c[i];
					i++;
				}
				else{
					ad+=b[b1];
					ans+=b[b1];
					b1++;
				}
			}
		}
		if(i>n&&b1>=cnt){
			break;
		}
		b[cnt++]=ad;
	}
	return ans;
}
int main()
{
	int t;
	cin>>t;
	while(t--){
		int n;
		scanf("%d%d",&n,&T);
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
		}
		sort(a+1,a+1+n);
		int l=2,r=n;
		int ans;
		while(l<=r){
			int mid=(l+r)/2;
			if(cal(n,mid)<=T){
				r=mid-1;
				ans=mid;
			} 
			else
			{
				l=mid+1;
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值