【题解】CF846C:Four Segments

原题传送门
a n s = 2 ( s u m i + s u m k s u m j ) s u m n ans=2(sum_i+sum_k-sum_j)-sum_n
对于每个 j j ,算出最优的 i , k i,k ,枚举 j j

Code:

#include <bits/stdc++.h>
#define maxn 5010
#define LL long long
using namespace std;
int n;
LL sum[maxn], pre[maxn], nxt[maxn];
int idpre[maxn], idnxt[maxn];

inline int read(){
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

int main(){
	n = read();
	for (int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + read();
	for (int i = 1; i <= n; ++i)
		if (sum[i] > pre[i - 1]) idpre[i] = i, pre[i] = sum[i];
		else idpre[i] = idpre[i - 1], pre[i] = pre[i - 1];
	nxt[n] = sum[n], idnxt[n] = n;
	for (int i = n - 1; i; --i)
		if (sum[i] > nxt[i + 1]) idnxt[i] = i, nxt[i] = sum[i];
		else idnxt[i] = idnxt[i + 1], nxt[i] = nxt[i + 1];
	LL ans = -1e9;
	int ansi, ansj, ansk;
	//LL ans = sum[n], ansi = n, ansj = n, ansk = n;
	//if (sum[n] < 0) ans = -sum[n], ansi = ansj = ansk = 0;
	for (int i = 0; i <= n; ++i)
		if (2LL * (pre[i] + nxt[i] - sum[i]) - sum[n] > ans)
			ans = 2LL * (pre[i] + nxt[i] - sum[i]) - sum[n], ansi = idpre[i], ansj = i, ansk = idnxt[i];
	printf("%d %d %d\n", ansi, ansj, ansk);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ModestCoder_/article/details/108365420