Pre
一道不太难的蓝题,有一点需要注意。
Solution
四次单调队列(少几次也可以,但是需要空间支持)。
Code
#include<bits/stdc++.h>
#define xx first
#define yy second
#define ll long long
using namespace std;
const int N = 3000000 + 5;
ll info[N], n, q[N], tail, head;
ll l[N], r[N], k;
int main () {
memset (r, 127, sizeof (r));
scanf ("%lld%lld", &k, &n);
for (int i = 1; i <= n; ++i) {
scanf ("%lld", &info[i]);
}
l[1] = 1;
tail = head = 1;
q[1] = 1;
for (int i = 2; i <= n; ++i) {
l[i] = l[i - 1];
while (tail >= head && info[q[head]] - info[i] > k) {
l[i] = max (q[head] + 1, l[i]);
head++;
}
while (tail >= head && info[q[tail]] < info[i]) {
tail--;
}
q[++tail] = i;
}
tail = head = 1;
q[1] = 1;
for (int i = 2; i <= n; ++i) {
l[i] = max (l[i], l[i - 1]);
while (tail >= head && info[q[head]] - info[i] < -k) {
l[i] = max (l[i], q[head] + 1);
head++;
}
while (tail >= head && info[q[tail]] >= info[i]) {
tail--;
}
q[++tail] = i;
}
tail = head = 1;
q[1] = n;
r[n] = n;
for (int i = n - 1; i >= 1; --i) {
r[i] = r[i + 1];
while (tail >= head && info[q[head]] - info[i] > k) {
r[i] = min (q[head] - 1, r[i]);
head++;
}
while (tail >= head && info[q[tail]] <= info[i]) {
tail--;
}
q[++tail] = i;
}
tail = head = 1;
q[1] = n;
for (int i = n - 1; i >= 1; --i) {
r[i] = min (r[i], r[i + 1]);
while (tail >= head && info[q[head]] - info[i] < -k) {
r[i] = min (r[i], q[head] - 1);
head++;
}
while (tail >= head && info[q[tail]] >= info[i]) {
tail--;
}
q[++tail] = i;
}
ll ans = 1, L = 1;
for (int i = 2; i <= n; ++i) {
L = max (L, l[i]);
ans = max (ans, i - L + 1);
}
printf ("%lld
", ans);
return 0;
}
Conclusion
第一次敲出代码样例都没有过就提交了,直接10分(竟然还有10分)。
发现有一个地方,在算出了限制位置(就是对于每一个点在区间内时,所选取的区间的最远的端点)之后,不能够直接
for (int i = 1; i <= n; ++i) {
ans = max (ans, r[i] - l[i] + 1);
}
因为区间内的数是非常有可能排斥的,正确的做法是
for (int i = 1; i <= n; ++i) {
L = max (L, l[i]);
ans = max (ans, i - L + 1);
}
就是枚举每一个点作为右端点,(DP)出左端点的最远取值。