HDU - 5884 Sort —— 优先队列+二分

Sort

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4974    Accepted Submission(s): 1233


 

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

 

题意:

给定n个数,每次可以选择k个数合并成他们的和,需要的花费也是他们的和,问最小的k,使得合并所有的数的花费不超过T。

思路:

哈夫曼树的构造方法,越小的数放在树越深的位置,即先合并小的数,合并后将其作为一个点再与其他点合并。

二叉的时候是可以直接这样构造的,但是如果是k叉的,这样构造就有可能使得根节点的子节点不够k个,这样构造出来的树肯定不是最优的,那么要怎么样构造呢。

一共有n个节点,每次选择k个合并成一个,就减少了n-1个节点,所以这样构造会有(n-1)%(k-1)个节点是多出来的,那么我们就可以先选这些个最小的节点合并,剩下的就一定可以构造成最优了。

至于原因,我的想法是这多出来的点一定要尽可能的深,因为要腾出空给其他的节点,所以要选择在最深的位置处的点就是最小的点先合并。

直接模拟合并应该是WA的,不知道为啥就T了,可能是不预先处理点多了吧,如果返回WA可能就会去找构造方法不对了...

#include <bits/stdc++.h>
using namespace std;
#define ll long long
int n;
ll cost;
ll num[100100];
ll pre[100100];
bool check(int x)
{
	priority_queue< ll,vector<ll>,greater<ll> >q;
	ll ans=0,sum=0;
	ll d=(n-1)%(x-1)+1;
	if(d>1)
	{
		ans=pre[d];
		q.push(pre[d]);
		for(int i=d+1;i<=n;i++)
		q.push(num[i]);
	}
	else
	{
		for(int i=1;i<=n;i++)
		q.push(num[i]);
	}
	while(!q.empty())
	{
		sum=0;
		for(int i=1;i<=x;i++)
		{
			sum+=q.top();
			q.pop();
		}
		ans+=sum;
		if(ans>cost)
		return false;
		if(!q.empty())
		q.push(sum);
	}
	if(ans<=cost)
	return true;
	else
	return false;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%lld",&n,&cost);
		for(int i=1;i<=n;i++)
		{
			scanf("%lld",&num[i]);
		}
		sort(num+1,num+1+n);
		pre[1]=num[1];
		for(int i=2;i<=n;i++)
		pre[i]=pre[i-1]+num[i];
		int l=2,r=n;
		int ans=n;
		while(l<=r)
		{
			int mid=(l+r)>>1;
			if(check(mid))
			{
				ans=mid;
				r=mid-1;
			}
			else
			{
				l=mid+1;
			}
		}
		printf("%d\n",ans);
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值