AtCoder Regular Contest 121 D - 1 or 2

题目链接:点我点我

Problem Statement

Snuke has a blackboard and NN candies. The tastiness of the ii-th candy is aiai.

He will repeat the operation below until he has no more candy.

  • Choose one or two of his candies and eat them (of course, they disappear). Then, write on the blackboard the total tastiness of the candies he has just chosen.

Snuke wants to minimize X−YXY, where XX and YY are the largest and smallest values written on the blackboard, respectively. Find the minimum possible value of X−YXY.

Constraints

  • All values in input are integers.
  • 1≤N≤50001N5000
  • −109≤ai≤109109ai109

Input

Input is given from Standard Input in the following format:

NN
a1a1 a2a2  aNaN

Output

Print the minimum possible value of X−YXY, where XX and YY are the largest and smallest values written on the blackboard, respectively.


Sample Input 1

3
1 2 4

Sample Output 1

1
  • One optimal sequence of operations is to eat the candies with the tastinesses of 11 and 22 in the first operation, and then eat the candies with the tastiness of 44 in the second operation.

Sample Input 2

2
-100 -50

Sample Output 2

0
  • It is optimal to eat both candies with the tastiness of −100100 and −5050 in the first operation.

Sample Input 3

20
-18 31 -16 12 -44 -5 24 17 -37 -31 46 -24 -2 11 32 16 0 -39 35 38

Sample Output 3

13



题意

给出 n 个数,每个数最多可以和另一个数结合(相加)而变成一个新数,当然也可以不操作,问最后序列中最大数-最小数的最小值是多少



题解

这个题目的官方题解给的太好了

首先很容易想到,要想最小化 \(maxx-minn\) 必须要缩小序列中所有数的 \('\)距离 \('\)

假设一个序列从小到大排序依次为

\[a_1,a_2,a_3......a_i,a_{i+1},......a_n \]

再假设 \(i\) 之前的数都是负数,且正数的个数多于负数的个数
那么

\[a_1+a_n,a_2+a_{n-1}.....a_{i-1}+a_{n-i+2} \]

这些数之间的 \('\)距离\('\) 没法被缩小了

剩下的数还有

\[a_i,a_{i+1},a_{i+2}.....a_{j} \]

这些数都是正数,而他们没有一个构造方法,有可能两个较小数相加变为一个较大数,也有可能不与其他数结合

其实这两种情况都是同一种情况,不与其他数结合不就是与 \(0\) 结合嘛。

所以算法复杂度 \(O(N^2)\)


以下代码采用 O(N2logN) 的方法,时间与正解相差 40 倍


const int N=3e5+5;
 
    ll n, m, _;
    int i, j, k;
    //ll a[N];
    vector<ll> v;

ll calc(int sz)
{
    int l = 0, r = sz - 1;
    ll maxx = -1e18, minn = 1e18;
    while(r >= l){
        if(l == r){
            minn = min(minn, v[l]);
            maxx = max(maxx, v[l]);
            break;
        }
        else{
            minn = min(minn, v[r] + v[l]);
            maxx = max(maxx, v[r] + v[l]);
        }
        r--;
        l++;
    }
    return maxx - minn;
}

signed main()
{
    //IOS;
    while(~sd(n)){
        rep(i, 0, n - 1) sll(_), v.pb(_);
        sort(all(v));
        ll minn = calc(n);
        rep(i, 1, n - 1){
            v.pb(0);
            sort(all(v));
            minn = min(minn, calc(n + i));
        }
        pll(minn);
        v.clear();
    }
    //PAUSE;
    return 0;
}
上一篇:力扣 1431. 拥有最多糖果的孩子 python


下一篇:leetCode134:分发糖果