【Problem Solution】Sequence Extreme

Title source: loj

Title description

Jiajia’s teacher wrote a series of n positive integers on the blackboard, and asked Jiajia to do the following: erase two numbers a and b each time, and then add a number a*b+ to the series 1. Continue this until there is one number left on the blackboard. Among all the numbers finally obtained by this operation method, the largest is max and the smallest is min, then the range of the sequence is defined as M=max-min.

As Jiajia is busy preparing for the final exam, please help him to calculate the corresponding range for the given series

Input format

In the first
row, a positive integer n represents the length of the sequence of positive integers; in the next n rows, enter a positive integer in each row.
The next line has a 0, which indicates the end of the data.

Output format

The output is only one line, which is the corresponding range.

Sample input

3
1
2
3
0

Sample output

2

Data range and tips

For all data, 0<=n<=50000, to ensure that all data calculations are within the range of 32-bit signed integers.

Ideas

Seeking the maximum and minimum, intuitively think of greed

Seeking max: Multiplying the smallest two in the
sequence of numbers each time Seeking min: Multiplying the two largest in the sequence of numbers each time

For this Yazi, every time I select the smallest two of the sequence, I use priority_queue. As for the largest two, it is easy to think of sorting the original sequence from largest to smallest. The larger multiplier is definitely better than the others. Small is bigger

code

#include<bits/stdc++.h>
using namespace std;
const int N=50010;
int n,a[N],b;
priority_queue<int,vector<int>,greater<int> >q;//小根堆 

void init()
{
    
    
	scanf("%d",&n);
	for (int i=1;i<=n;i++) 
	{
    
    
		int x;
		scanf("%d",&a[i]);
		q.push(a[i]);
	}
    scanf("%d",&b);
}

int cmp(int x,int y) {
    
     return x>y; }

int work_max()
{
    
    
	int tmp;
	while (!q.empty())
	{
    
    
		tmp=q.top();
		q.pop();
		tmp=tmp*q.top()+1;
		q.pop();
		if (q.empty()) break; 
		q.push(tmp);
	}
	return tmp;
}

int work_min()
{
    
    
	sort(a+1,a+1+n,cmp); //从大到小
	int anss=a[1];
	for (int i=2;i<=n;i++)
		anss=anss*a[i]+1;	
	return anss;
}
int main()
{
    
    
	init();
	int maxx=work_max(); 
    int minn=work_min();
    cout<<maxx-minn<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45485187/article/details/102798470