Problem Description
给定k 个排好序的序列s1 , s2,……, sk , 用2 路合并算法将这k 个序列合并成一个序列。假设所采用的2 路合并算法合并2 个长度分别为m和n的序列需要m + n -1次比较。试设计一个算法确定合并这个序列的最优合并顺序,使所需的总比较次数最少。
为了进行比较,还需要确定合并这个序列的最差合并顺序,使所需的总比较次数最多。
对于给定的k个待合并序列,计算最多比较次数和最少比较次数合并方案。
Input
输入数据的第一行有1 个正整数k(k≤1000),表示有k个待合并序列。接下来的1 行中,有k个正整数,表示k个待合并序列的长度。
Output
输出两个整数,中间用空格隔开,表示计算出的最多比较次数和最少比较次数。
Sample Input
4 5 12 11 2
Sample Output
78 52
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int> q1;//大顶堆
priority_queue<int,vector<int>,greater<int> > q2;//小顶堆
int k;
cin>>k;
int x;
for(int i=0;i<k;i++){
cin>>x;
q1.push(x);
q2.push(x);
}
int sum;
int maxValue =0,minValue = 0;
int a,b;
while(q1.size()>1){
a = q1.top();
q1.pop();
b = q1.top();
q1.pop();
sum = a+b;
maxValue += (sum-1);
q1.push(sum);
a =q2.top();
q2.pop();
b = q2.top();
q2.pop();
sum = a+b;
minValue +=(sum-1);
q2.push(sum);
}
printf("%d %d\n",maxValue,minValue);
return 0;
}