原题链接:https://www.luogu.com.cn/problem/P1886
题意解读:单调队列模版题。
解题思路:
采用双端队列维护单调的序列,单调队列三部曲:
1、去头,当窗口内元素个数超过k,队头出队
2、去尾,当要加入的元素会破坏单调性,队尾出队
3、入队,将元素的下标存入队列
每一次入队后,队头元素即为窗口最值。
100分代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
int n, k;
int a[N];
int q[N], head , tail; //手写双端队列
int main()
{
cin >> n >> k;
for(int i = 1; i <= n; i++) cin >> a[i];
head = 0, tail = -1; //初始化队头,队尾指针
for(int i = 1; i <= n; i++)
{
//去头
while(head <= tail && i - q[head] + 1 > k) head++;
//去尾
while(head <= tail && a[i] < a[q[tail]]) tail--;
//入队
q[++tail] = i;
if(i >= k) cout << a[q[head]] << " ";
}
cout << endl;
head = 0, tail = -1; //初始化队头,队尾指针
for(int i = 1; i <= n; i++)
{
//去头
while(head <= tail && i - q[head] + 1 > k) head++;
//去尾
while(head <= tail && a[i] > a[q[tail]]) tail--;
//入队
q[++tail] = i;
if(i >= k) cout << a[q[head]] << " ";
}
}
标签:head,P1886,洛谷题,入队,int,tail,单调,队列,模板 From: https://www.cnblogs.com/jcwy/p/18404788