Sort 二分 + (队列 + sort 代替优先队列)

Sort
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1695 Accepted Submission(s): 431

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

题意:t组数据,每次输入N,T,然后输入N个数,进行合并操作,将其中k个数合并为一个数后,代价为这k个数的和,并将这个和放入剩余的数列中,一直合并下去……最后合并为一个数,要求总的代价不超过T,求最小的k值;

思路:k叉哈夫曼树,很明显k值在2~N之间,而且k越大总的代价越小,那么利用这个性质我们可以对k值进行二分查找,我开始时想的用优先队列做,但超时了……我们可以对数组先从小到大排序,然后利用一个队列装合并得到的数,每次取数组和队列中较小的数,注意用一个变量pos记录数组取完数后的下一个位置,队列中取完数后要删除这个数,为什么可以这样呢? 因为每次合并得到的数一定小于等于上次合并得到的数,所以最小数一是 数组pos位置和队列首中的较小者。另外,这些数的个数不一定满足k个k个的合并,所以要先合并不足的几个数,什么时候不满足呢,(N-1)%(k-1)!=0 时;为了使总代价最小,我们先合并前面的几个数。

AC代码:

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const int maxn = 100000+5;
int a[maxn];
int n,T;

int cal(int k)
{
    queue<long long> q;
    int pos = 0;
    long long sum = 0;
    if((n-1)%(k-1)!=0)
    {
        pos = (n-1)%(k-1)+1;
        for(int i=0;iwhile(poslong long sum2 = 0;
        for(int i=0;iif(!q.empty())
            {
                if(posa[pos])
                {
                    sum2 += a[pos];
                    sum += a[pos];
                    pos++;
                }
                else
                {
                    sum2 += q.front();
                    sum += q.front();
                    q.pop();
                }
            }
            else if(posif(sum>T) return 0;
        if(posif(sum>T) return 0;
    else return 1;
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%lld",&n,&T);
        for(int i=0;iscanf("%d",&a[i]);
        sort(a,a+n);
        int l = 2, r = n,mid;
        while(l<=r)
        {
            mid = (l + r)>>1;
            int f = cal(mid);
            if(f==0) l = mid + 1;
            else r = mid - 1;
        }
        printf("%d\n",l);
    }
    return 0;
}

你可能感兴趣的:(ACM网络赛,STL)