题解:P17521 [ECUSTPC 2026 Fall] 天外来物

· · 题解

我们发现,第 i 个数对答案的贡献只取决于 i-1 和 i+1 两个位置的选法。我们设 f_{i,0/1} 表示确定了前 i 个数的符号,第二维是 0 表示先选 i 再选 i+1;第二维是 1 表示先选 i+1 再选 i。

转移:f_{i,0}=\max(f_{i-1,1}+a_i,f_{i-1,0}-a_i),对应 i\to i-1\to i+1 和 i-1\to i\to i+1 两种选法;f_{i,1}=\max(f_{i-1,1}-a_i,f_{i-1,0}+a_i),对应 i+1\to i\to i-1 和 i+1\to i-1\to i 两种选法。

代码如下,可供参考:

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+10;
int T,n,a[N],f[N][2];
signed main(){
    cin>>T;
    while(T--){
        cin>>n;
        for(int i=1;i<=n;i++)cin>>a[i];
        f[1][0]=a[1];f[1][1]=-a[1];
        for(int i=2;i<n;i++){
            f[i][0]=max(f[i-1][1]+a[i],f[i-1][0]-a[i]);
            f[i][1]=max(f[i-1][1]-a[i],f[i-1][0]+a[i]);
        }
        if(n==1)cout<<a[1]<<'\n';
        else cout<<max(f[n-1][0]-a[n],f[n-1][1]+a[n])<<'\n';
    }
    return 0;
}