AtCoder Regular Contest 121 D - 1 or 2
题目链接:点我点我
Problem Statement
Snuke has a blackboard and candies. The tastiness of the -th candy is .
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 , where and are the largest and smallest values written on the blackboard, respectively. Find the minimum possible value of .
Constraints
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
Output
Print the minimum possible value of , where and 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 and in the first operation, and then eat the candies with the tastiness of 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 and 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\) 必须要缩小序列中所有数的 \('\)距离 \('\)
假设一个序列从小到大排序依次为
再假设 \(i\) 之前的数都是负数,且正数的个数多于负数的个数
那么
这些数之间的 \('\)距离\('\) 没法被缩小了
剩下的数还有
这些数都是正数,而他们没有一个构造方法,有可能两个较小数相加变为一个较大数,也有可能不与其他数结合
其实这两种情况都是同一种情况,不与其他数结合不就是与 \(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;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步