Sliding Window POJ - 2823 (优先队列 或者 滚动rmq 或者 单调栈 )

An array of size  n ≤ 10  6 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

优先队列

#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");
}







你可能感兴趣的:(dhkj)