题解:CF1421E Swedish Heroes

· · 题解

解法

提供一个无需 DP 的做法。

考虑钦定每个数的正负,即构造序列 \{c_1,c_2,\dots,c_n\},c_i\in\{1, -1\},使得 ans = \sum_{i=1}^n c_i a_i 最大。

一个序列 c 合法,当且仅当能执行若干次操作,每次操作将两个相邻的 1 合成 -1,或将两个相邻的 -1 合成 1,使得最后只剩下一个 1。

假设 c 中有 x 个 1,y 个 -1。可以发现一次操作后,它们的个数差 d=x-y 会有 3 的变化量,而执行 n-1 次后 d 会变成 1。据此可以得到一个 c 合法的必要条件:

d\equiv1\pmod 6, & n\equiv1\pmod 2, \\ d\equiv4\pmod 6, & n\equiv0\pmod 2. \end{cases}

据此,可以枚举合法的 d\in[-n,n],将 a 排序后贪心地令较大的 x 个数对应的系数为 1,其余的为 -1,通过前缀和 \mathcal{O}(1) 计算每种情况的答案,取最大值即可。

然而考虑到如果 c 中 1 和 -1 交错出现,即没有相邻的 1 或 -1 却仍有多个数,c 就不满足条件。结合上述的必要条件,只需考虑 c 形如 \{1,-1,1,\dots,-1,1\} 的情况:

最后记得特判掉 n=1 的情况。

时间复杂度 \mathcal{O}(n\log n),瓶颈在排序上,但常数相当小,只跑了 78ms。

代码

#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;
}