跳到正文

算法·理论

单调队列进阶

scguo约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟

版本

  1. v1当前

P3512

思路

这是一个非常经典的求极差题目。

既然是要求最大值减去最小值,那么,我们可以是使用单调队列。不过,因为不固定长度,所以第一眼就会想到二分,其实二分也可以,不过要卡常。所以,我们使用 O(n)O(n) 的一遍单调队列。

虽然是不固定长度,但是不合法的元素还是要删除,只是不需要删除过时元素,毕竟我们也不知道长度是多少。

但是,如果此时的极差超过了 kk,那么就需要移动了。我们优先将小的移动,然后更新一下变量 pospos 为 quel+1que_l + 1。

最后,我们需要对 i−pos+1i - pos + 1,也就是长度取最大值,结束。

Code:

C++
#include <bits/stdc++.h>
#define c1 l1 <= r1
#define c2 l2 <= r2
using namespace std;
using LL = long long;
const int N = 3e6 + 5;
LL k, n, a[N], que1[N], que2[N], l1, r1, l2, r2;
int main() {
  cin.tie(0)->sync_with_stdio(false);
  cin >> k >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i];
  }
  l1 = 1, l2 = 1;
  int mx = 0, pos = 1;
  for (int i = 1; i <= n; ++i) {
    while (c1 && a[que1[r1]] <= a[i]) {
      r1--;
    }
    while (c2 && a[que2[r2]] >= a[i]) {
      r2--;
    }
    que1[++r1] = i;
    que2[++r2] = i;
    while (c1 && c2 && a[que1[l1]] - a[que2[l2]] > k) {
      if(que1[l1] < que2[l2]) {
        pos = que1[l1] + 1;
        l1++;
      } else {
        pos = que2[l2] + 1;
        l2++;
      }
    }
    mx = max (mx, i - pos + 1);
  }
  cout << mx;
  return 0;
}

P10059

思路

这题直接求出极差,然后输出,再跑一遍二分,结束。

Code:

C++
#include <bits/stdc++.h>
#define c1 l1 <= r1
#define c2 l2 <= r2
#define LL long long
using namespace std;
const int N = 1e5 + 5;
LL n, k, a[N], X, que1[N], l1, r1, que2[N], l2, r2;
bool check(int x) {
  fill(que1 + 1, que1 + n + 1, 0);
  fill(que2 + 1, que2 + n + 1, 0);
  l1 = 1, r1 = 0;
  l2 = 1, r2 = 0;
  LL T = 1e18;
  int cnt = 0;
  for (int i = 1; i <= n; ++i) {
    while (c1 && a[que1[r1]] <= a[i]) r1--;
    while (c2 && a[que2[r2]] >= a[i]) r2--;
    que1[++r1] = i;
    que2[++r2] = i;
    while (c1 && que1[l1] + x <= i) l1++;
    while (c2 && que2[l2] + x <= i) l2++;
    if(i >= x) {
      cnt += ((a[que1[l1]] - a[que2[l2]]) >= X);
    }
  }
  return cnt >= k;
}
void solve() {
  X = 1e18;
  cin >> n >> k;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i];
  }
  l1 = 1, r1 = 0;
  l2 = 1, r2 = 0;
  for (int i = 1; i <= n; ++i) {
    while (c1 && a[que1[r1]] <= a[i]) r1--;
    while (c2 && a[que2[r2]] >= a[i]) r2--;
    que1[++r1] = i;
    que2[++r2] = i;
    while (c1 && que1[l1] + (n - k + 1) <= i) l1++;
    while (c2 && que2[l2] + (n - k + 1) <= i) l2++;
    if(i >= n - k + 1) X = min (X, a[que1[l1]] - a[que2[l2]]);
  }
  cout << X << ' ';
  int lt = 0, rt = n - k + 2;
  while (lt + 1 < rt) {
    int mid = lt + rt >> 1;
    if(check(mid)) {
      rt = mid;
    } else {
      lt = mid;
    }
  }
  cout << rt << '\n';
  return;
}
int main() {
  cin.tie(0)->sync_with_stdio(false);
  int T;
  cin >> T;
  while (T--) {
    solve();
  }
  return 0;
}

The End.

原文