题目:
将一个数组里面的数排成一个闭环,要求是每个数的左右两个数之和大于该数。
思路:
将数组进行排序,如果最大的数小于第二大与第三大之和,则是可以进行排成闭环的,将该排序的数组中的前两个交换即可。此时,因为是排序了的,必然满足每一个数小于其左右两个数之和。
代码:
#include<iostream>
#include <algorithm>
using namespace std;
int Arr[100001];
int main() {
int n;
cin >> n;
int temp = n;
while(temp--){
cin >> Arr[temp];
}
sort(Arr, Arr + n);
if(Arr[n - 1] >= Arr[n - 2] + Arr[n - 3]){
cout << "NO" << endl;
return 0;
}
cout << "YES" << endl;
int tempItem = Arr[n - 1];
Arr[n - 1] = Arr[n - 2];
Arr[n - 2] = tempItem;
for(int i = 0; i < n - 1; i++){
cout << Arr[i] << " ";
}
cout << Arr[n - 1] << endl;
}