Codeforces Round #572 (Div. 2)-B

B.
Number Circle
time limit per test 1 second
memory limit per test 256 megabytes
inputstandard input
outputstandard output
You are given n numbers a1,a2,…,an. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?

For example, for the array [1,4,5,6,7,8], the arrangement on the left is valid, while arrangement on the right is not, as 5≥4+1 and 8>1+6.
在这里插入图片描述

Input
The first line contains a single integer n (3≤n≤105) — the number of numbers.

The second line contains n integers a1,a2,…,an (1≤ai≤109) — the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).

Output
If there is no solution, output “NO” in the first line.

If there is a solution, output “YES” in the first line. In the second line output n numbers — elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.

Examples
inputCopy
3
2 4 3
outputCopy
YES
4 2 3
inputCopy
5
1 2 3 4 4
outputCopy
YES
4 4 2 1 3
inputCopy
3
13 8 5
outputCopy
NO
inputCopy
4
1 10 100 1000
outputCopy
NO
Note
One of the possible arrangements is shown in the first example:

4<2+3;

2<4+3;

3<4+2.

One of the possible arrangements is shown in the second example.

No matter how we arrange 13,8,5 in a circle in the third example, 13 will have 8 and 5 as neighbors, but 13≥8+5.

There is no solution in the fourth example.

思路:
贪心 先排序如果把最大的放在第二位,第二大放在第一位,第三大放在第三位,那么假如这个最大的比相邻的这两个和都大就无须再判断直接输出NO反之本来的思路是从剩下的数中找到第一个比前两个数的差值大的元素 后来一直WA仔细想想这个数组既然已经升序那么直接把剩下的按顺序在后面排列就行 至于后面的为啥可以按这个顺序排列 是因为从第三个数来看,第三个数填入的是倒数第三个就是第三大的数如果我们把第四大的数放在它后面,那么第四大的数就被一个比他大的数和一个比他小的数夹着了就一定符合题意了。向后推,后面又因为是升序排列,所以后面的都比前一个数大,再加上一个数肯定比前面那个数大了,所以就无须进行选择第一个比差值大的数了。

代码

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=2e5+5;
int num[maxn];
int main ()
{
	int n;
	cin>>n;
	for(int i=0;i<n;i++) cin>>num[i];
	sort(num,num+n);
	if(num[n-1]>=num[n-2]+num[n-3]) cout<<"NO";
	else {
		cout<<num[n-2]<<" "<<num[n-1]<<" "<<num[n-3]<<" ";
		for(int i=n-4;i>=0;i--) cout<<num[i]<<" ";
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值