第1部分 基礎算法(提高篇)--第1章 貪心算法1427:數列極差

1427:數列極差

時間限制: 1000 ms 內存限制: 65536 KB
提交數: 1771 通過數: 797
【題目描述】
在黑板上寫了N個正整數作成的一個數列,進行如下操作:每一次擦去其中的兩個數a和b,然後在數列中加入一個數a×b+1,如此下去直至黑板上剩下一個數,在所有按這種操作方式最後得到的數中,最大的max,最小的爲min,則該數列的極差定義爲M=max−min。

【輸入】
第一行,一個數爲N;

第二行,N個數。

【輸出】
輸出極差。

【輸入樣例】
3
1 2 3
【輸出樣例】
2


思路:貪心題,一組數字每次去掉兩個 x , y,再加入一個新的 x*y+1,如果保證最後得到一個最大的數字,那麼每次去掉兩個最小的數字,換來一個較大的數字,這樣最後結果會越來越大 如果保證最後得到一個最小的數字,那麼每次去掉兩個最大的數字,換來一個新數字由於你去掉了兩個最大的數字,所以這個操作過程使得結果呈現遞減趨勢,結果就最小。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
int n,maxn,minn,s,x,y,ca[10001];
priority_queue<int,vector<int>,greater<int> >a;//優先隊列從小到大 

priority_queue<int>b;
int main(){
	scanf("%d",&n);
	for(int i = 1; i <= n; i++)
	scanf("%d",&ca[i]);
   	for(int i = 1; i <= n; i++)
	a.push(ca[i]);
	for(int i = 1; i <= n; i++)
	b.push(ca[i]);
	for(int i = 1; i <= n - 1; i++) //最大值
	{
		x = a.top();
		a.pop();
		y = a.top();
		a.pop();
		a.push(x * y + 1);
	}
	maxn = a.top();
	for(int i = 1; i <= n - 1; i++)//最小值
	{
		x = b.top();
		b.pop();
		y = b.top();
		b.pop();
		b.push(x * y + 1);
	} 
	minn = b.top();
	printf("%d",maxn - minn);
	return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章