luogu P1121 环状最大两段子段和

时间:2022-01-25 10:42:48

嘟嘟嘟

一道说难也难说简单也简单的dp题。

我觉得我的(有篇题解)做法就属于特别简单的。

平时遇到环的问题都是断环为链,但这道题给了一种新的思路。

观察一下,最后的答案无非就这两种:xxx--xx---xxxx

                   ----xxx-----xx---

对于第二种,有一个特别好的做法:正着求一遍最大子串和,再倒着求一遍,然后枚举断点拼接起来。

至于第一种情况,只要很巧妙的转化一下,就变成了第二种:正反两遍求最小子串和,然后拿总和减一下就成了。至于最小子串和,可以取相反数,就变成了求最大子串和。

所以这道题就做完了。

但是如果序列中只有一个正数的话,就不能再求第一种情况,比如-3 -2 4 -5 -6,按上述算法求出来的是0,。所以特判掉就好。

 #include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-;
const int maxn = 2e5 + ;
inline ll read()
{
ll ans = ;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) {last = ch; ch = getchar();}
while(isdigit(ch)) {ans = ans * + ch - ''; ch = getchar();}
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < ) x = -x, putchar('-');
if(x >= ) write(x / );
putchar(x % + '');
} int n, sum = , a[maxn]; int f[maxn], g[maxn];
int query()
{
Mem(f, -0x3f); Mem(g, -0x3f);
for(int i = ; i <= n; ++i) f[i] = max(f[i - ], ) + a[i];
for(int i = n; i; --i) g[i] = max(g[i + ], ) + a[i];
for(int i = ; i <= n; ++i) f[i] = max(f[i], f[i - ]);
for(int i = n; i; --i) g[i] = max(g[i], g[i + ]);
int ret = -INF;
for(int i = ; i < n; ++i) ret = max(ret, f[i] + g[i + ]);
return ret;
} int main()
{
n = read();
int tot = ;
for(int i = ; i <= n; ++i) a[i] = read(), sum += a[i], tot += a[i] > ;
int ans1 = query();
if(tot == ) {write(ans1), enter; return ;}
for(int i = ; i <= n; ++i) a[i] = -a[i];
int ans2 = sum + query();
if(!ans2) ans2 = -INF;
write(max(ans1, ans2)), enter;
return ;
}

至于难得做法吗,无非就是特别复杂的dp转移方程,有兴趣的可以看别的题解~