题解:P15906 [TOPC 2024] Business Magic
题意
给定
思路
假设我们选择区间
简化计算,我们维护两个前缀和:
sum[x]:原数组r 的前缀和。s[x]:绝对值数组|r| 的前缀和。
那么就有:
很显然这个暴力会 TLE。
考虑优化。我们把上面的式子按变量
令
当我们从小到大枚举 m1 在遍历
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#define int long long
#define endl "\n"
#define INF 0x3f3f3f3f3f3f3f3f
using namespace std;
const int N = 1e6 + 10;
inline int read()
{
int x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9')
{
if(ch == '-')
f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9')
x = x*10+ch-'0',ch = getchar();
return x * f;
}
int a[N],sum[N],s[N];
signed main()
{
int n = read();
sum[0] = s[0] = 0;
for(int i = 1;i<=n;++i)
{
a[i] = read();
sum[i] = sum[i-1]+a[i];
s[i] = s[i-1]+abs(a[i]);
}
int ans = 0,m1 = 0;
for(int i = 1;i<=n;++i)
{
m1 = max(m1,s[i-1]-2*sum[i-1]);
ans = max(ans,2*sum[i]-s[i]+m1);
}
cout<<ans+s[n]<<endl;
return 0;
}
本题告诉我们,做不出来的时候一定要打暴力找思路。