本帖最后由 Ewan-Ahiouy 于 2023-8-23 20:25 编辑 #include <iostream>
int n, k, l, r, ll, rr, lll, rrr, a[200011];
long long ans = -1145141919810, ans2 = -1145141919810, a1, a2, s[200011];
int main() {
scanf("%d%d", &n, &k);
if (n > 10000) {
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
s[i] = s[i - 1] + a[i];
}
for (int i = 1; i <= n - k + 1; i++) {
a1 = s[i + k - 1] - s[i - 1];
if (a1 > ans) {
l = i;
r = i + k - 1;
ans = a1;
}
}
for (int i = 1; i <= n - k + 1; i++) {
ll = i, rr = i + k - 1;
if ((r >= ll && ll >= l) || (r >= rr && rr >= l));
else {
a2 = s[i + k - 1] - s[i - 1];
if (a2 > ans2) {
lll = ll;
rrr = rr;
ans2 = a2;
}
}
}
// printf("l = %d\tr = %d\tans=%lld\n", l, r, ans);
// printf("l2 = %d\tr2 = %d\tans2=%lld\n", lll, rrr, ans2);
printf("%lld\n", ans + ans2);
} else {
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
s[i] = s[i - 1] + a[i];
}
for (int i = 1; i <= n - k + 1; i++) {
a1 = s[i + k - 1] - s[i - 1];
for (int j = i + k; j <= n - k + 1; j++) a2 = s[j + k - 1] - s[j - 1], ans = std::max(ans, a1 + a2);
}
printf("%lld\n", ans);
}
return 0;
}
这题我吸取了一个教训:其实没有必要一个方法走到黑,可以针对性的进行判断和修改
我的代码如果n > 10000的话,就用贪心,否则爆搜
|