Sort Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 5069 Accepted Submission(s): 1263
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 首先想的是二分+优先队列 : 然后发现O(nlgnlgn) TLE了. 需要注意的点 对于合并果子问题,要先处理零头 零头的意思是 例如 1 2 3 4 k = 3 则最后剩下 4 6 ->10 cost = 6 + 10 = 16 此时零头为1,所以开始时应该先处理零头,合并1 2 -> 3 得到 3 3 4 所以cost 为 3 + 10 = 13. 怎么求零头? 因为每次合并k个会失去k-1个数,最后只要剩下一个数,所以要失去n-1个数,所以零头为 (n-1)%(k-1) ,所以应该首先处理(零头+1)(失去零头个数)个最小的数。 然后用双队列处理,队列1保存原有的ai,队列2放置合并的数, 每次取出队列1和队列2一起的k个最小数,经分析发现,放入队列2的数据有单调递增性质,所以解法无误。复杂度为nlgn 如果用优先队列,需要用读入优化(我没试) #include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
#include <map>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5 + 10;
const int maxm = 10000 + 10;
typedef pair<int,int> P;
typedef long long LL;
int n,c;
int a[maxn];
bool check(int mid)
{
queue<int> q1,q2;
for(int i = 0; i < n; i++) q1.push(a[i]);
LL curc = 0;
int t = (n-1)%(mid-1);
if(t)
{
int p = 0;
for(int i = 0; i < t+1 && !q1.empty(); i++) {p += q1.front();q1.pop();}
curc += p;
q2.push(p);
}
while(1)
{
int p = 0;
for(int i = 0; i < mid ; i++)
{
int x = INF,y = INF;
if(q1.empty() && q2.empty()) break;
if(!q1.empty()) x = q1.front();
if(!q2.empty()) y = q2.front();
if(x < y) {p += x;q1.pop();}
else {p += y;q2.pop();}
}
curc += p;
//cout << mid << " "<< curc << endl;
if(curc > c) return true;
if(q1.empty() && q2.empty()) break;
q2.push(p);
}
//cout << mid << " " << curc << endl;
if(curc > c) return true;
else return false;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&c);
for(int i = 0; i < n; i++) scanf("%d",&a[i]);
sort(a,a+n);
int st = 1, ed = n;
while(ed - st > 1)
{
int mid = st + (ed-st)/2;
if(check(mid)) st = mid;
else ed = mid;
}
printf("%d\n",ed);
}
return 0;
}
|