Neven @ 2023-09-16 23:50:49
本来想手动写一个双端队列玩玩,然后用几个题目测试一下,结果过不去。
using namespace std;
template <typename new_dype>
class Deque{
struct De_node{
new_dype val;
De_node *next = NULL, *prev = NULL;
}*tail, *head;
public:
Deque():tail(NULL), head(NULL){
return;
}
void pop_back(){
if(tail){
De_node *temp = tail;
tail = tail->prev;
if(tail)
tail->next = NULL;
delete temp;
}
}
void pop_front(){
if(head){
De_node *temp = head;
head = head->next;
if(head)
head->prev = NULL;
delete temp;
}
}
void push_back(new_dype num){
De_node *newt = new De_node();
newt->val = num;
if(tail){
tail->next = newt;
newt->prev = tail;
}else{
newt->prev = NULL;
}
if(!head) head = newt;
tail = newt;
}
void push_front(new_dype num){
De_node *newt = new De_node();
newt->val = num;
if(head){
newt->next = head;
head->prev = newt;
}else{
newt->next = NULL;
}
if(!tail) tail = newt;
head = newt;
}
new_dype front(){
if(head)
return head->val;
}
new_dype back(){
if(tail)
return tail->val;
}
void clear(){
while(head){
De_node *temp = head;
head = head->next;
delete temp;
}
tail = NULL;
}
bool empty(){
return !(tail && head);
}
};
int n, k;
struct node{
int id, num;
}a[1000010];
Deque<node>q;
int main(){
cin >> n >> k;
for(int i = 1; i <= n; i++){
cin >> a[i].num;
a[i].id = i;
}
for(int i = 1; i <= n; i++){//最小值
while(!q.empty() && a[i].num < q.back().num){
q.pop_back();
}
q.push_back(a[i]);
while(i - q.front().id >= k){
q.pop_front();
}
if(i >= k){
cout << q.front().num << " ";
}
}
q.clear();
cout << endl;
for(int i = 1; i <= n; i++){//最大值
while(!q.empty() && a[i].num > q.back().num){
q.pop_back();
}
q.push_back(a[i]);
while(i - q.front().id >= k){
q.pop_front();
}
if(i >= k){
cout << q.front().num << " ";
}
}
return 0;
}
by NO_OI_NO_LIFE @ 2023-10-15 14:46:34
看了很多题解都觉得很麻烦,核心就十几行,如下(不知道您过了没
#include <bits/stdc++.h>
#define maxn 200010
#define maxm 500010
#define ull unsigned long long
#define ll long long
#define INF 123456789
#define il inline
using namespace std;
int n,k,dq[2000006],a[2000006];
int main(){
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
cin>>n>>k;
int h=1,t=0;
for(int i=1;i<=n;i++){
cin>>a[i];
while(h<=t&&dq[h]<=i-k) h++;
while(h<=t&&a[dq[t]]>=a[i]) t--;
dq[++t]=i;
if(i>=k) cout<<a[dq[h]]<<" ";
}
cout<<endl;
h=1,t=0;
for(int i=1;i<=n;i++){
while(h<=t&&dq[h]<=i-k) h++;
while(h<=t&&a[dq[t]]<=a[i]) t--;
dq[++t]=i;
if(i>=k) cout<<a[dq[h]]<<" ";
}
return 0;
}