跳到正文

剪贴板

剪贴板 23hrtdy4

原文
剪贴板信息

剪贴板信息

收录
更新

单调队列

结构体封装:

C++
struct Monotonic_queue_min {
	static const int maxn = 1000006;
	int hd = 1, tl = 0, k, q[maxn], p[maxn], a[maxn];
	void insert(int x){
		while (hd <= tl && q[tl] >= a[x]) tl--;
		q[++tl] = a[x];
		p[tl] = x;
	}
	void pop(int x){
		while (hd <= tl && p[hd] <= x - k) hd++;
	}
	int find() {
		return q[hd];
	}
};
struct Monotonic_queue_max {
	static const int maxn = 1000006;
	int hd = 1, tl = 0, k, q[maxn], p[maxn], a[maxn];
	void insert(int x){
		while (hd <= tl && q[tl] <= a[x]) tl--;
		q[++tl] = a[x];
		p[tl] = x;
	}
	void pop(int x){
		while (hd <= tl && p[hd] <= x - k) hd++;
	}
	int find() {
		return q[hd];
	}
};

例题:P1886 滑动窗口 /【模板】单调队列

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
struct Monotonic_queue_min {
	static const int maxn = 1000006;
	int hd = 1, tl = 0, k, q[maxn], p[maxn], a[maxn];
	void insert(int x){
		while (hd <= tl && q[tl] >= a[x]) tl--;
		q[++tl] = a[x];
		p[tl] = x;
	}
	void pop(int x){
		while (hd <= tl && p[hd] <= x - k) hd++;
	}
	int find() {
		return q[hd];
	}
} mq_min;
struct Monotonic_queue_max {
	static const int maxn = 1000006;
	int hd = 1, tl = 0, k, q[maxn], p[maxn], a[maxn];
	void insert(int x){
		while (hd <= tl && q[tl] <= a[x]) tl--;
		q[++tl] = a[x];
		p[tl] = x;
	}
	void pop(int x){
		while (hd <= tl && p[hd] <= x - k) hd++;
	}
	int find() {
		return q[hd];
	}
} mq_max;
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n, k;
	cin >> n >> k;
	mq_max.k = mq_min.k = k;
	for (int i = 1; i <= n; i++) {
		int x;
		cin >> x;
		mq_max.a[i] = mq_min.a[i] = x;
	}
	for (int i = 1; i <= n; i++) {
		mq_min.insert(i);
		mq_min.pop(i);
		if (i >= k)
			cout << mq_min.find() << " ";
	}
	cout << endl;
	for (int i = 1; i <= n; i++) {
		mq_max.insert(i);
		mq_max.pop(i);
		if (i >= k)
			cout << mq_max.find() << " ";
	}
	return 0;
}