极差,set解法

 题目内容

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

输入描述

输入包含多个测试集.每个测试集的第一行N表示正整数序列长度(0<=N<=50000),随后第二行是N个正整数.当N为0时结束.


输出描述

每个结果一行.


输入样例

3
3 5 7


输出样例

4

 

第一眼以为是哈夫曼树的问题,后来觉得是贪心问题,就每次取最大的,就会得到最大值,每次找最小的,最后得到最小值

利用set可以自动排序来解题。

 

//#include<bits/stdc++.h>
#include<iostream>
#include<vector>
#include<cstdio>
#include<cmath>
#include<set>
#include<algorithm>
#define ll long long
using namespace std;
int main(){
	ll n;
	while( cin>>n && n != 0 ){
		if( n <= 2 ){
			cout<<0<<endl;
			continue;
		} 
		
		set<ll>x;
		set<ll>x1;
		ll max_sum = 1 , min_sum = 1;
		for( int i = 0 ; i < n ; i++ ){
			ll num;
			cin>>num;
			if( i >= 2 ) x.insert(num);
			else max_sum *= num;
			
			if( i >= n - 2 ) min_sum *= num;
			else x1.insert(num);
		}
		
		x.insert(max_sum + 1);
		x1.insert(min_sum + 1);
		while( x.size() > 1 ){
			max_sum = 1;
			set<ll>::iterator it = x.begin();
			max_sum *= *it;
			x.erase(it);
			set<ll>::iterator it1 = x.begin();
			max_sum *= *it1;
			x.erase(it1);
			x.insert(max_sum + 1);
		}

		while( x1.size() > 1 ){
			min_sum = 1;
			set<ll>::iterator it = x1.end();
			min_sum *= *--it;
			x1.erase(it);
			set<ll>::iterator it1 = x1.end();
			min_sum *= *--it1;
			x1.erase(it1);
			x1.insert(min_sum + 1);
		}
		set<ll>::iterator it = x.begin();
		set<ll>::iterator it1 = x1.begin();
		cout<<*it - *it1<<endl;
	} 
	return 0;
}

oj数据太弱,这个时间复杂度我总感觉要超时...

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值