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.
8 3 1 3 -1 -3 5 3 6 7Sample Output
-1 -3 -3 -3 3 3 3 3 5 5 6 7
优先队列
#include
#include
#include
#include
using namespace std;
int a[1000005];
int ans[1000005];
struct cmp1
{
bool operator () (const int a1,const int a2)
{
return a[a1]>a[a2];
}
};
struct cmp2
{
bool operator () (const int a1,const int a2)
{
return a[a1],cmp1> s;
priority_queue ,cmp2> s2;
if(m>=n) m=n;
for(i=1;i<=m-1;i++)
{
scanf("%d",&a[i]);
s.push(i);
s2.push(i);
}
for( ; i<=n; i++)
{
scanf("%d",&a[i]);
s.push(i);
s2.push(i);
while(i-s.top()>=m)
s.pop();
while(i-s2.top()>=m)
s2.pop();
if(i!=m) printf(" ");
printf("%d",a[s.top()]);
ans[i]=a[s2.top()];
}
printf("\n");
for(i=m; i<=n; i++)
{
if(i!=m) printf(" ");
printf("%d",ans[i]);
}
printf("\n");
}
滚动rmq
#include
#include
#include
#include
#include
using namespace std;
int ma[1000005][2],mi[1000005][2];
int n,m,k;
void rmq()
{
for(int j=1;j<=k;j++)
{
for(int i=1;i<=n;i++)
{
if(i+(1<n) break;
ma[i][j&1]=max(ma[i][(j+1)&1],ma[i+(1<
单调栈
#include
#include
#include
#include
#include
#include
using namespace std;
int n,m,l,r;
int a[1000005],b[1000005];
int main()
{
scanf("%d%d",&n,&m);
l=0,r=-1;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<=n;i++)//单调递增
{
while(l<=r&&a[i]<=a[b[r]]) r--;//如果进入新的值不递增,那么一直退栈直到递增
b[++r]=i;
while(i-b[l]>=m) l++;
if(i>=m) printf("%d ",a[b[l]]);
}
printf("\n");
l=0,r=-1;
for(int i=1;i<=n;i++)//单调递减
{
while(l<=r&&a[i]>a[b[r]]) r--; //如果进入新的值不递减,那么一直退栈直到递减
b[++r]=i;
while(i-b[l]>=m) l++;
if(i>=m) printf("%d ",a[b[l]]);
}
printf("\n");
}