Time Limit: 2 sec / Memory Limit: 1024 MB
Score: 400400 points
Problem Statement
Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N−1N−1 players who happen to be there. These NN players, including you, are numbered 11 through NN, and the friendliness of Player ii is AiAi.
The NN players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.
When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 00.
What is the maximum total comfort the NN players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?
Constraints
- All values in input are integers.
- 2≤N≤2×1052≤N≤2×105
- 1≤Ai≤1091≤Ai≤109
Input
Input is given from Standard Input in the following format:
NN A1A1 A2A2 …… ANAN
Output
Print the maximum total comfort the NN players can get.
Sample Input 1 Copy
4 2 2 1 3
Sample Output 1 Copy
7
By arriving at the place in the order Player 4,2,1,34,2,1,3, and cutting into the circle as shown in the figure, they can get the total comfort of 77.
They cannot get the total comfort greater than 77, so the answer is 77.
Sample Input 2 Copy
7 1 1 1 1 1 1 1
Sample Output 2 Copy
6
题意:给你n个数,从n个数中每次取出一个数字添加到环中,第一次添加得到的值为0,后面每次添加,得到左右相邻元素最小的值。
解题思路:通过观察可知,除了第二次添加的时候得到一次最大的元素,接着的元素都是得到两次,因为新添加的元素可以放在所求元素左边和右边
大概就是这个效果,我们通过观察可以发现每个 目标最大值 可以被选中两次,那么我们只需要把这n个数字排序后,把前n/2个元素相加再乘2
当然我们在这里发现了个问题,就是边界的问题,第n/2个元素到底 + or !+ ,其实上面这个例子很明显的给出了答案,当n为奇数的时候+
当n为偶数的时候 !+,于是我们可以得到代码:
#include<cstdio> #include<queue> #include<algorithm> #define ll long long #define maxn 200005 using namespace std; bool cmp(int a,int b) { return a>b; } int main(void) { int n; ll a[maxn];while(~scanf("%d",&n)) { long long sum=0; for(int i=0;i<n;++i) { scanf("%lld",&a[i]); } sort(a,a+n,cmp); sum=a[0]; for(int i=1;i<n/2;++i) { sum+=2*a[i]; } if(n&1) sum+=a[n/2]; printf("%lld ",sum); } }