参考博客
单调队列例题
#include <bits/stdc++.h>
using namespace std;
struct node
{
int val;
int index;
};
int a[1000005];
int main()
{
ios::sync_with_stdio(false);
int n, k;
cin >> n >> k;
for(int i = 1; i <= n; i++) cin >> a[i];
deque<node> q;
for(int i = 1; i <= n; i++){
while(q.size() && q.front().index <= (i - k))
q.pop_front();
while(q.size() && q.back().val >= a[i])
q.pop_back();
q.push_back(node{a[i], i});
if(i >= k) cout << q.front().val << " ";
}
while(q.size()) q.pop_front();
cout << endl;
for(int i = 1; i <= n; i++){
while(q.size() && q.front().index <= (i - k))
q.pop_front();
while(q.size() && q.back().val <= a[i])
q.pop_back();
q.push_back(node{a[i], i});
if(i >= k) cout << q.front().val << " ";
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
struct node
{
int val;
int index;
};
int a[2000005];
int main()
{
ios::sync_with_stdio(false);
int n, k;
cin >> n >> k;
for(int i = 1; i <= n; i++) cin >> a[i];
deque<node> q;
for(int i = 1; i <= n; i++){
while(q.size() && q.front().index <= (i - k))
q.pop_front();
while(q.size() && q.back().val <= a[i])
q.pop_back();
q.push_back(node{a[i], i});
if(i >= k) cout << q.front().val << endl;
}
return 0;
}