优先队列

题目网址:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=109331#problem/C

Description

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 positionMinimum valueMaximum 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 nintegers 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

题意:给了n个数,给了k,求前k个数(即a[0]到a[k-1])中的最大数和最小数,然后求a[1]到a[k]中的最大数和最小数,……,依次下去a[n-k]到a[n-1]中的最大数和最小数。

解题思路:使用STL中的优先队列priority_queue进行求解。开两个优先队列,优先队列中插入的是元素的下标,队列中按元素值的从大到小和从小到大优先放在上面。每插入一个元素后,将队列中已经跑出窗口外的元素删除,队列的top元素所指的元素就是该窗口内的最大或最小值。

#include<algorithm>
#include<queue>
#include<vector>
#include<cstdio>
using namespace std;
int a[1000010];
int cn1[1000010],cn2[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];
    }
};
priority_queue<int,vector<int>,cmp1>q1;
priority_queue<int,vector<int>,cmp2>q2;

int main()
{
    int n,k,d1,d2;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        d1=0;d2=0;
        for(int i=0;i<n;i++)
        scanf("%d",&a[i]);
        for(int i=0;i<k;i++)
        {
            q1.push(i);
            q2.push(i);
        }
        cn1[d1++]=q1.top();
        cn2[d2++]=q2.top();///存储前k个数中的最大数和最小数;
        for(int i=k;i<n;i++)
        {
            q1.push(i);
            q2.push(i);
            while(i-q1.top()>=k)
                q1.pop();///剔除已经不在范围里(窗口里)的数;
            while(i-q2.top()>=k)
                q2.pop();
            cn1[d1++]=q1.top();
            cn2[d2++]=q2.top();///存储窗口里的最大数和最小数;
        }
       for(int i=0;i<=n-k;i++)
            printf("%d%c",a[cn1[i]],(i<n-k)?' ':'
');
       for(int i=0;i<=n-k;i++)
            printf("%d%c",a[cn2[i]],(i<n-k)?' ':'
');
    }
    return 0;
}


原文地址:https://www.cnblogs.com/chen9510/p/5286957.html