AtCoder Regular Contest 121 D - 1 or 2

Bcoi發表於2021-06-05

題目連結:點我點我

Problem Statement

Snuke has a blackboard and N candies. The tastiness of the i-th candy is ai.

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 XY, where X and Y are the largest and smallest values written on the blackboard, respectively. Find the minimum possible value of XY.

Constraints

  • All values in input are integers.
  • 1N5000
  • 109ai109

Input

Input is given from Standard Input in the following format:

N
a1 a2  aN

Output

Print the minimum possible value of XY, where X and Y 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 1 and 2 in the first operation, and then eat the candies with the tastiness of 4 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 100 and 50 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;
}

相關文章