数列极差问题(JLOJ2493)

数列极差问题,在黑板上写了N个正整数组成的一个数列,进行如下操作:每次擦去其中的两个数a和b,然后在数列中加入一个数a×b+1,如此下去直至黑板上 剩下一个数,在所有按这种操作方式最后得到的数中,最大的为max,最小的为min, 则该数列的极差定义为M=max-min。

输入

第一行输入正整数N(1<N<100),表示有N个数;

第二行输入N个正整数,表示数列。

输出

输出极差M。

样例输入 Copy

6
4 3 5 1 7 9

样例输出 Copy

1688
贪心思想解决
分析:
设存在3个数 x,y,z (x < y < z) 则 num1 = xyz + z  num2 = xyz + y  num3 = xyz + x
很明显num1 > num2 > num3
因此数列从小到大为max值,从大到小为min值
//贪心算法  (数列极差问题)  (LJOJ2493)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>//优先队列
using namespace std;
priority_queue<int,vector<int>,greater<int> > q1;//小跟堆    升序序列
priority_queue<int,vector<int>,less<int> > q2;//大根堆       降序序列
int main()
{
    ios::sync_with_stdio(false);
    int N,tmp;//一共有N个数
    cin>>N;
    for(int i=0;i!=N;++i)
    {
        cin>>tmp;
        q1.push(tmp);
        q2.push(tmp);
    }
    int maxx,minn;
    for(int i=0;i!=N-1;++i)//i个数,进行N-1次合并
    {
        int value1 = q1.top();
        q1.pop();
        int value2 = q1.top();
        q1.pop();
        int value = value1 * value2 + 1;
        q1.push(value);
    }
    maxx = q1.top();
    for(int i=0;i!=N-1;++i)//i个数,进行N-1次合并
    {
        int value1 = q2.top();
        q2.pop();
        int value2 = q2.top();
        q2.pop();
        int value = value1 * value2 + 1;
        q2.push(value);
    }
    minn = q2.top();
    cout<<maxx - minn<<endl;
}

 

posted on 2019-08-30 20:36  chengyulala  阅读(939)  评论(0编辑  收藏  举报

导航