一年前入门的题目了,当时没写出来,现在填坑
题目
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.
坑点
-
明显用二分 + 贪心,二分k,每次选择cost最少的来合并
-
假如枚举的 k,那么每次合并消耗的是 k−1个,最后合并完后剩下一个,所以总消耗是 n−1 个,如果 (n−1)%(k-1)!=0,会存在零头,要先合并 零头 + 1个序列
-
有点卡常
方法1
-
用priority_queue有点卡,可以先把n个序列从小到大排序,优先队列每次要check函数内定义,n <= 10^5,这样优先队列内存占用小于 1M (栈空间) 所以可以开的下,输入输出用scanf printf
-
时间复杂度 O(n * logn * logn j) 出队入队次数 * 二分次数 * 优先队列单次插入删除
-
code
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 1e5 + 10;
int a[N];
ll n,t;
bool check(int k){
priority_queue< int, vector<int> , greater<int> > q1;
for(int i = 0; i < n; ++i)
q1.push(a[i]);
int ct = 2,sz = (n - 1) % (k - 1);
ll res = 0;
if(sz){
for(int i = 0; i <= sz; ++i){
res += q1.top();
q1.pop();
}
q1.push(res);
}
ll z;
while(q1.size() > 1 && res <= t){
z = 0;
for(int i = 0; i < k && q1.size(); ++i){
z += q1.top();
q1.pop();
}
q1.push(z);
res += z;
}
return res <= t;
}
int main(){
int T; scanf("%d",&T);
while(T--){
scanf("%lld %lld",&n,&t);
for(int i = 0; i < n; ++i)
{
scanf("%d",&a[i]);
}
sort(a, a + n);
int l = 2,r = n,ans = n;
while(l <= r && l < ans){
int m = (l + r) >> 1;
if(check(m)){
ans = min(ans,m);
r = m - 1;
}else l = m + 1;
}
printf("%d\n",ans);
}
return 0;
}
方法2
-
先排序,然后用两个队列模拟优先队列,这样就少了一个log。很好过
-
时间复杂度 O(nlogn)
-
code
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 1e5 + 10;
int a[N];
ll n,t;
bool check(int k){
queue<ll> q1,q2;
for(int i = 0; i < n; ++i)
q1.push(a[i]);
int ct = 2,sz = (n - 1) % (k - 1);
ll res = 0;
if(sz){
for(int i = 0; i <= sz; ++i){
res += q1.front();
q1.pop();
}
q1.push(res);
}
ll x,y;
while(q1.size() + q2.size() > 1 && res <= t){
ll z = 0;
for(int i = 0; i < k && q1.size() + q2.size(); ++i){
if(q1.size() && q2.size()){
x = q1.front();
y = q2.front();
if(x < y){
z += x;
q1.pop();
}else{
z += y;
q2.pop();
}
}else if(q1.size()){
ct = 2;
z += q1.front();
q1.pop();
}else{
ct = 1;
z += q2.front();
q2.pop();
}
}
if(ct == 1)
q1.push(z);
else q2.push(z);
res += z;
}
return res <= t;
}
int main(){
int T; scanf("%d",&T);
while(T--){
scanf("%lld %lld",&n,&t);
for(int i = 0; i < n; ++i)
{
scanf("%d",&a[i]);
}
sort(a, a + n);
int l = 2,r = n,ans = n;
while(l <= r && l < ans){
int m = (l + r) >> 1;
if(check(m)){
ans = min(ans,m);
r = m - 1;
}else l = m + 1;
}
printf("%d\n",ans);
}
return 0;
}