给定k 个排好序的序列, 用 2 路合并算法将这k 个序列合并成一个序列。
假设所采用的 2 路合并算法合并 2 个长度分别为m和n的序列需要m+n-1 次比较。试设
计一个算法确定合并这个序列的最优合并顺序,使所需的总比较次数最少。
为了进行比较,还需要确定合并这个序列的最差合并顺序,使所需的总比较次数最多。
输入格式:
第一行有 1 个正整数k,表示有 k个待合并序列。
第二行有 k个正整数,表示 k个待合并序列的长度。
输出格式:
输出最多比较次数和最少比较次数。
输入样例:
在这里给出一组输入。例如:
4
5 12 11 2
输出样例:
在这里给出相应的输出。例如:
78 52
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int n;
cin>>n;
int min=0,max=0;
priority_queue<int, vector<int>, greater<int>> heap1; //创建小根堆 最少比较次数
priority_queue<int> heap2; //创建大根堆 最多比较次数
int x;
for(int i=0;i<n;i++)
{
cin>>x;
heap1.push(x);
heap2.push(x);
}
while(heap1.size()>1)
{
int a=heap1.top(); heap1.pop();
int b=heap1.top(); heap1.pop();
heap1.push(a+b);
min+=a+b-1;
int x=heap2.top(); heap2.pop();
int y=heap2.top(); heap2.pop();
heap2.push(x+y);
max+=x+y-1;
}
cout<<max<<" "<<min;
return 0;
}