2016 年青岛网络赛---Sort(k叉哈夫曼)

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=5884

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
 
 
Recommend
wange2014   |   We have carefully selected several similar problems for you:  5891 5890 5889 5887 5886 
 
题意:to组数据,每次输入N,T,然后输入N个数,进行合并操作,将其中k个数合并为一个数后,代价为这k个数的和,并将这个和放入剩余的数列中,一直合并下去......最后合并为一个数,要求总的代价不超过T,求最小的k值;
 
思路:k叉哈夫曼树,很明显k值在2~N之间,而且k越大总的代价越小,那么利用这个性质我们可以对k值进行二分查找,我开始时想的用优先队列做,但超时了......我们可以对数组先从小到大排序,然后利用一个队列装合并得到的数,每次取数组和队列中较小的数,注意用一个变量pos记录数组取完数后的下一个位置,队列中取完数后要删除这个数,为什么可以这样呢? 因为每次合并得到的数一定小于等于上次合并得到的数,所以最小数一是 数组pos位置和队列首中的较小者。另外,这些数的个数不一定满足k个k个的合并,所以要先合并不足的几个数,什么时候不满足呢,(N-1)%(k-1)!=0 时;
 
代码如下:
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <queue>
#include <cmath>
#include <string.h>
using namespace std;
int N;
long long T;
long long a[]; int calc(int k)
{
queue<long long>q;
int pos=;
long long sum=;
if((N-)%(k-)!=&&N>k) ///如果不能k个k个合并到底,则先合并筹不足k个的;
{
pos=(N-)%(k-)+;
for(int i=;i<pos;i++) sum+=a[i];
q.push(sum);
}
while()
{
long long sum2=;
for(int i=; i<k; i++)
{
if(!q.empty())
{
if(pos<N&&q.front()>a[pos])
{
sum2+=a[pos];
sum+=a[pos];
pos++;
}
else
{
sum2+=q.front();
sum+=q.front();
q.pop();
}
}
else if(pos<N)
{
sum2+=a[pos];
sum+=a[pos];
pos++;
}
else goto endw;
}
if(sum>T) return ;
if(pos<N||!q.empty())
q.push(sum2);
}
endw:;
if(sum<=T) return ;
else return ;
} int main()
{
int to;
scanf("%d",&to);
while(to--)
{
scanf("%d%lld",&N,&T);
for(int i=; i<N; i++)
scanf("%lld",&a[i]);
sort(a,a+N);
int l=,r=N,mid;
while(l<=r)
{
mid=(l+r)>>;
int f=calc(mid);
if(f==) l=mid+;
else r=mid-;
}
printf("%d\n",l);
}
return ;
}
上一篇:Java集合ArrayList源码解读


下一篇:SQL注入常用语句