最优合并问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
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()
{
int k;
int x;
scanf("%d", &k);
int sum1, sum2;
priority_queue <int > queue1;
priority_queue <int , vector<int >, greater<int > > queue2;
for(int i = 1; i <= k; i++)
{
scanf("%d", &x);
queue1.push(x);
queue2.push(x);
}
sum1 = 0;
while(queue1.size() > 1)
{
int num1 = queue1.top();
queue1.pop();
int num2 = queue1.top();
queue1.pop();
queue1.push(num1 + num2);
sum1 += num1 + num2 - 1;
}
sum2 = 0;
while(queue2.size() > 1)
{
int num1 = queue2.top();
queue2.pop();
int num2 = queue2.top();
queue2.pop();
queue2.push(num1 + num2);
sum2 += num1 + num2 - 1;
}
printf("%d %d\n", sum1, sum2);
}