1. 程式人生 > >poj2823 Sliding Window (優先佇列)

poj2823 Sliding Window (優先佇列)

/*
題意:
 有N個數,每次從左到右選取M個數,第一行選取每個區間中的最小值輸出,第二行選取最大值並輸出。
*/
# include <stdio.h>
# include <string.h>
# include <algorithm>
# include <queue>
# include <vector>
using namespace std;
int a[1000010],maxx[1000010],minn[1000010];
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]<a[a2];
    }
};
int main()
{
    priority_queue<int,vector<int>,cmp1>q1;//小

    priority_queue<int,vector<int>,cmp2>q2;
    int n,i,k;
    while(~scanf("%d%d",&n,&k))
    {
        for(i=1; i<=n; i++)
            scanf("%d",&a[i]);
        while(!q1.empty())
            q1.pop();
        while(!q2.empty())
            q2.pop();

        for(i=1; i<=k; i++)
        {
            q1.push(i);
            q2.push(i);
        }
        int cot=0;
        maxx[cot]=a[q2.top()];

        minn[cot++]=a[q1.top()];

        for(i=k+1 ; i<=n; i++)
        {
            q1.push(i);
            q2.push(i);

            while(i-q1.top()>=k)
                q1.pop();
            while(i-q2.top()>=k)
                q2.pop();
            maxx[cot]=a[q2.top()];

            minn[cot++]=a[q1.top()];
        }
        for(i=0; i<cot; i++)
        {
            if(i==cot-1)
                printf("%d\n",minn[i]);
            else
                printf("%d ",minn[i]);
        }

        for(i=0; i<cot; i++)
        {
            if(i==cot-1)
                printf("%d\n",maxx[i]);
            else
                printf("%d ",maxx[i]);
        }



    }
    return 0;
}