Description
给定 k 个升序序列 s1, s2, …, sk, 用 2 路合并算法将这 k 个序列合并成一个升序序列. 假设所采用的 2 路合并算法合并 2 个长度分别为 m 和 n 的序列需要 m + n -1 次比较.
本题要求对于给定的 k 个待合并序列, 试计算合并这个序列的最优合并顺序所需的总比较次数最差合并顺序所需的总比较次数.
Input
有多个测试用例. 每个测试用例的第一行有一个正整数 k, 表示有 k 个待合并序列. 接下来的一行中有 k 个正整数, 表示 k 个待合并序列的长度.
输入直至没有数据为止.
Output
对于每个测试用例, 在一行上输出最多比较次数和最少比较次数.
Sample Input
4
5 12 11 2
Sample Output
78 52
分析
2 5 11 12
最少比较次数:2+5-1+7+11-1+18+12-1=52
12 11 5 2
最多比较次数:
3 4 5 6 12
最少比较次数 3+4-1+5+6-1+7+11-1+18+12-1=55
不能安排序这样算3+4-1+7+5-1+12+6-1+18+12-1=56
要每一次选最小的那两个
#include<iostream>
#include <queue>
using namespace std;
int main() {
int k;
int n;
int tmp;
while(cin>>k) {
int maxc = 0;
int minc = 0;
priority_queue<int> a; //最大堆
priority_queue<int, vector<int>, greater<int> > b; // 最小堆
for (int i = 0; i < k;++i) {
cin >> n;
a.push(n);
b.push(n);
}
while(a.size()>=2) {
tmp = a.top();
a.pop();
tmp += a.top();
a.pop();
maxc += tmp - 1;
a.push(tmp);
}
while(b.size()>=2) {
tmp = b.top();
b.pop();
tmp += b.top();
b.pop();
minc += tmp - 1;
b.push(tmp);
}
cout << maxc << " " << minc << endl;
}
return 0;
}