跳到正文

个人记录

CF1359D Yet Another Yet Another Task 题解

legendgod约 3 分钟
原文
文章信息与版本

文章信息

发布
2021年4月13日
收录
2026年5月2日
更新
2026年11月11日
篇幅
约 3 分钟

版本

  1. v1当前

CF1359D Yet Another Yet Another Task

题目思路很好,写这篇博客的人很 sb。


考虑对于一个区间其贡献是,其权值和减去最大值。

我们发现 ai∈[−30,30]a_i \in [-30, 30] 而且答案肯定不会小于 0。考虑枚举最大值。

之后进行更新答案。假设枚举到的最大值是 x 那么我们答案就是 V[l,r]−xV_{[l, r]} - x 可以发现不会存在最大值不在当前区间的情况。

如果最大值不在当前区间,那么减去了 x 一定不会更优。

之后考虑每一个区间真正产生了贡献的情况,必定是这个区间的权值之和 > 0 的时候。我们可以双指针维护这个区间权值之和大于 0。当区间右端点遍历到的元素比枚举的 x 还要大的时候,我们要从新开始计算区间。

C++
#include <bits/stdc++.h>
using namespace std;

//#define Fread

#ifdef Fread
#define getchar() ((p1 == p2 && p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin)) ? EOF : *p1 ++)
char buf[1 << 21], *p1, *p2;
#endif // Fread

template <typename T>
void r1(T &x) {
	x = 0;
	char c(getchar());
	int f(1);
	for(; !isdigit(c); c = getchar()) if(c == '-') f = -1;
	for(; isdigit(c);c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
	x *= f;
}

const int maxn = 2e5 + 5;
const int maxm = maxn << 1;

typedef int room[maxn];

int n, m;
int a[maxn];

signed main() {
//    freopen(".in", "r", stdin);
//    freopen(".out", "w", stdout);
	int i, j;
    r1(n);
    for(i = 1; i <= n; ++ i) r1(a[i]);
    int res(0);
    for(int x = 1; x <= 30; ++ x) {
        int now(0);
        for(int r = 1; r <= n; ++ r) {
            now += a[r];
            if(a[r] > x) now = 0;
            if(now < 0) now = 0;
            res = max(res, now - x);
        }
    }
    printf("%d\n", res);
	return 0;
}
/*
11
3 0 1 -2 5 -5 -1 0 3 2 2

4
*/
原文