Chinaunix首页 | 论坛 | 博客
  • 博客访问: 350699
  • 博文数量: 122
  • 博客积分: 5000
  • 博客等级: 大校
  • 技术积分: 1191
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-24 11:12
文章分类

全部博文(122)

文章存档

2010年(122)

我的朋友

分类: C/C++

2010-04-06 17:11:59

一、问题描述

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

二、解题思想

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

参考http://hi.baidu.com/xiaohanhoho/blog/item/b020b923aac13cfad6cae228.html

三、代码

 

#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
int a[1000011];//数组数据

int OutMin[1000011];//最小值

int OutMax[1000011];//最大值

int cnt1=0;
int cnt2=0;
int n,k;

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 i;
    scanf("%d%d",&n,&k);
    if(k>n)
        k=n;
    for(i=1;i<=n;++i)
    {
        scanf("%d",&a[i]);
    }
    for(i=1;i<=k;++i)
    {
        Q1.push(i);
        Q2.push(i);
    }
    OutMin[cnt1++]=a[Q1.top()];
    OutMax[cnt2++]=a[Q2.top()];
    for(i=k+1;i<=n;++i)
    {
        Q1.push(i);
        Q2.push(i);
        while(i-Q1.top()>=k)
            Q1.pop();
        OutMin[cnt1++]=a[Q1.top()];
        while(i-Q2.top()>=k)
            Q2.pop();
        OutMax[cnt2++]=a[Q2.top()];
    }
    
    for(i=0;i<=(n-k);++i)
    {
        printf("%d%c", OutMin[i], (i < n - k) ? ' ' : '\n');
        
    }
    for(i=0;i<=(n-k);++i)
    {
        printf("%d%c", OutMax[i], (i < n - k) ? ' ' : '\n');
    }
    return 0;
}


阅读(5248) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~