1. 程式人生 > 實用技巧 >AtCoder Beginner Contest 173 D - Chat in a Circle

AtCoder Beginner Contest 173 D - Chat in a Circle

D - Chat in a Circle


Time Limit: 2 sec / Memory Limit: 1024 MB

Score:400400points

Problem Statement

Quickly after finishing the tutorial of the online gameATChat, you have decided to visit a particular place withN1N−1players who happen to be there. TheseNNplayers, including you, are numbered

11throughNN, and thefriendlinessof PlayeriiisAiAi.

TheNNplayers 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 getscomfortequal 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 of00.

What is the maximum total comfort the

NNplayers 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.
  • 2N2×1052≤N≤2×105
  • 1Ai1091≤Ai≤109

Input

Input is given from Standard Input in the following format:

NN
A1A1 A2A2  ANAN

Output

Print the maximum total comfort theNNplayers can get.


Sample Input 1Copy

Copy
4
2 2 1 3

Sample Output 1Copy

Copy
7

By arriving at the place in the order Player4,2,1,34,2,1,3, and cutting into the circle as shown in the figure, they can get the total comfort of77.

They cannot get the total comfort greater than77, so the answer is77.


Sample Input 2Copy

Copy
7
1 1 1 1 1 1 1

Sample Output 2Copy

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\n",sum);
    }
}