版权声明:反正也没有人会转,下一个 https://blog.csdn.net/drtlstf/article/details/82932079
Description
佳佳的老师在黑板上写了一个由 n 个正整数组成的数列,要求佳佳进行如下操作:每次擦去其中的两个数 a 和 b,然后在数列中加入一个数 a×b+1,如此下去直至黑板上剩下一个数为止,在所有按这种操作方式最后得到的数中,最大的为 max,最小的为 min, 则该数列的极差定义为 M=max−min。
由于佳佳忙于准备期末考试,现请你帮助他,对于给定的数列,计算出相应的极差 M。
Input
第一行为一个正整数 n 表示正整数序列的长度;
在接下来的 n 行中,每行输入一个正整数。
接下来的一行有一个 0,表示数据结束。
Output
输出只有一行,为相应的极差 d。
Sample Input
3
1
2
3
0
Sample Output
2
HINT
对于全部数据,0≤n≤500000,保证所有数据计算均在 32 位有符号整数范围内。
贪心过程:
1:每次对最大的两个数进行操作
2.每次对最小的两个数进行操作
#include <iostream>
#include <queue>
using namespace std;
priority_queue<int, vector<int>, greater<int> > q;
priority_queue<int> q2;
int main(void)
{
int n, x, y, x2, y2;
while (scanf("%d", &n), n)
{
while (n--)
{
scanf("%d", &x);
q.push(x);
q2.push(x);
}
while (q.size() > 1) // 贪心
{
x = q.top(); // 两个队列同时进行
q.pop();
y = q.top();
q.pop();
x2 = q2.top();
q2.pop();
y2 = q2.top();
q2.pop();
q.push(x * y + 1);
q2.push(x2 * y2 + 1);
}
printf("%d\n", q.top() - q2.top());
q.pop(); // 保证下一轮队列为空
q2.pop();
}
return 0;
}