题解:CF1421E Swedish Heroes
解法
提供一个无需 DP 的做法。
考虑钦定每个数的正负,即构造序列
一个序列
假设
据此,可以枚举合法的
然而考虑到如果
-
同样贪心地令所有系数为 $1$ 的 $a_i$ 中最小的一个系数为 $-1$,所有系数为 $-1$ 的 $a_i$ 中的最大的一个系数为 $1$,这样能保证 $d$ 不变的情况下损失最小; -
一定存在某次操作使得形如 $\{1,1,1,1\}\to\{1,-1,1\}$,但可以操作形如 $\{1,1,1,1\}\to\{-1,1,1\}$ 来避免,于是不存在此情况。
最后记得特判掉
时间复杂度
代码
#include<bits/stdc++.h>
using namespace std;
constexpr int N = 2e5 + 1;
int n;
int a[N], id[N];
bool check() {
for(int i = 1; i <= (n >> 1); ++i) if(id[i] & 1) return false;
return true;
}
long long sum[N];
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
cin >>n;
for(int i = 1; i <= n; ++i) cin >>a[i];
if(n == 1) {cout <<a[1] <<'\n'; return 0;}
for(int i = 1; i <= n; ++i) id[i] = i;
sort(id + 1, id + n + 1, [](const int x, const int y)->bool{return a[x] < a[y];});
for(int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + a[id[i]];
long long ans = -1e18;
for(int d = (n & 1 ? -5 : -2); d >= -n; d -= 6) {
const int y = (n - d) >> 1;
ans = max(ans, sum[n] - 2 * sum[y]);
}
for(int d = (n & 1 ? 1 : 4); d <= n; d += 6) {
const int y = (n - d) >> 1;
if(d == 1 && check()) ans = max(ans, sum[n] - 2 * (sum[y + 1] - a[id[y]]));
else ans = max(ans, sum[n] - 2 * sum[y]);
}
cout <<ans <<'\n';
return 0;
}