Description
An array of size n ≤ 106 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example: The array is [1 3 -1 -3 5 3 6 7], and k is 3.
Window position | Minimum value | Maximum value |
---|
[1 3 -1] -3 5 3 6 7 | -1 | 3 | 1 [3 -1 -3] 5 3 6 7 | -3 | 3 | 1 3 [-1 -3 5] 3 6 7 | -3 | 5 | 1 3 -1 [-3 5 3] 6 7 | -3 | 5 | 1 3 -1 -3 [5 3 6] 7 | 3 | 6 | 1 3 -1 -3 5 [3 6 7] | 3 | 7 |
Your task is to determine the maximum and minimum values in the sliding window at each position.
Input
The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line.
Output
There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values.
Sample Input 8 3
1 3 -1 -3 5 3 6 7
Sample Output -1 -3 -3 -3 3 3
3 3 5 5 6 7
这道题可以用两个单调队列分别维护最大值和最小值,时间复杂度为O(n)(注意不要使用STL的queue,不然可能会TLE),下面是程序: #include<queue>
#include<stdio.h>
#include<iostream>
using namespace std;
const int N=1000005;
struct node{
int w,t;
}a[N];
struct que{
int q[N],l,r;
que(){
l=0;
r=1;
}
void pop_front(){
l=(l+1)%N;
}
void pop_back(){
r=(r+N-1)%N;
}
void push_front(int n){
q[l]=n;
l=(l+N-1)%N;
}
void push_back(int n){
q[r]=n;
r=(r+1)%N;
}
int front(){
return q[(l+1)%N];
}
int back(){
return q[(r+N-1)%N];
}
bool empty(){
return (l+1)%N==r;
}
};
que q1,q2;
int ans[N][2];
int read(){
int s=0,f=1;
char c=getchar();
while((c<'0'||c>'9')&&c!='-'){
c=getchar();
}
if(c=='-'){
f=-1;
}
while(c>='0'&&c<='9'){
s*=10;
s+=c-'0';
c=getchar();
}
return s*f;
}
int main(){
int n,k,i,tp;
n=read();
k=read();
for(i=1;i<=n;i++){
scanf("%d",&a[i].w);
a[i].t=i;
}
for(i=1;i<=k;i++){
tp=q1.back();
while(!q1.empty()&&a[i].w<a[tp].w){
q1.pop_back();
tp=q1.back();
}
q1.push_back(i);
tp=q2.back();
while(!q2.empty()&&a[i].w>a[tp].w){
q2.pop_back();
tp=q2.back();
}
q2.push_back(i);
}
ans[0][0]=q1.front();
ans[0][1]=q2.front();
for(i=k+1;i<=n;i++){
tp=q1.front();
while(!q1.empty()&&a[tp].t<=i-k){
q1.pop_front();
tp=q1.front();
}
tp=q1.back();
while(!q1.empty()&&a[i].w<a[tp].w){
q1.pop_back();
tp=q1.back();
}
q1.push_back(i);
tp=q2.front();
while(!q2.empty()&&a[tp].t<=i-k){
q2.pop_front();
tp=q2.front();
}
tp=q2.back();
while(!q2.empty()&&a[i].w>a[tp].w){
q2.pop_back();
tp=q2.back();
}
q2.push_back(i);
ans[i-k][0]=q1.front();
ans[i-k][1]=q2.front();
}
for(i=0;i<n-k+1;i++){
printf("%d ",a[ans[i][0]].w);
}
putchar('\n');
for(i=0;i<n-k+1;i++){
printf("%d ",a[ans[i][1]].w);
}
putchar('\n');
return 0;
}
|