有一个长为 nn 的序列 aa,以及一个大小为 kk 的窗口。现在这个从左边开始向右滑动,每次滑动一个单位,求出每次滑动后窗口中的最大值和最小值。
例如:
The array is [1,3,-1,-3,5,3,6,7][1,3,−1,−3,5,3,6,7], and k = 3k=3。
输入格式
输入一共有两行,第一行有两个正整数 n,kn,k。 第二行 nn 个整数,表示序列 aa
输出格式
输出共两行,第一行为每次窗口滑动的最小值
第二行为每次窗口滑动的最大值
输入输出样例
输入 #1复制
8 3
1 3 -1 -3 5 3 6 7
输出 #1复制
-1 -3 -3 -3 3 3
3 3 5 5 6 7
说明/提示
【数据范围】
用双端队列来下维护单调队列,实现队首为区间的最大值或者最小值
#include<bits/stdc++.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <map>
#include <stack>
#include <set>
#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <cstdio>
#define ls (p<<1)
#define rs (p<<1|1)
using namespace std;
const int maxn=1e6;
int a[maxn],b[maxn],id[maxn];
struct node{
int val,id;
};
void solve(){
int n,m;
cin>>n>>m;
node st[maxn];
for(int i=1;i<=n;i++){
cin>>st[i].val;
st[i].id=i;
}
deque<node>de1;
deque<node>de2;
int cnt=0;
for(int i=1;i<=n;i++){
while(!de1.empty()&&st[i].val>=de1.back().val){//维护最大值
de1.pop_back();
}
while(!de2.empty()&&st[i].val<=de2.back().val){
de2.pop_back();
}
de1.push_back(st[i]);
de2.push_back(st[i]);
while(i-m>=de1.front().id)
de1.pop_front();
while(i-m>=de2.front().id)
de2.pop_front();
if(i>=m){
a[++cnt]=de1.front().val;
b[cnt]=de2.front().val;
}
}
for(int i=1;i<=cnt;i++)
cout<<b[i]<<" ";
cout<<endl;
for(int i=1;i<=cnt;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int main()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
solve();
system("pause");
return 0;
}