滑动窗口问题

给定一个数组a, 求长度为m的连续区间的最大值.

 

使用单调队列, 时间复杂度O(n) .

 

#include<bits/stdc++.h>
using namespace std;

const int N = 1005;

int A, n;
int a[N];
int mx[N];

struct data {
    int p, v;
};
deque<data> Q;

void Push(data t)
{
    while ((!Q.empty()) && Q.back().v < t.v) Q.pop_back();
    Q.push_back(t);
}

void GETMAX()
{
    for (int i = 1; i < n; ++ i) {
        Push((data) {i, a[i]});
    }
    for (int i = n; i <= A; ++ i) {
        Push((data) {i, a[i]});
        while (!Q.empty() && Q.front().p < i - n + 1) Q.pop_front();
        mx[i] = Q.front().v;
    }
}

int main()
{
    scanf("%d%d", &A, &n);
    for (int i = 1; i <= A; ++ i)
        scanf("%d", &a[i]);
    GETMAX();
    for (int i = n; i <= A; ++ i)
        printf("[%d,%d] --> %d\n", i - n + 1, i, mx[i]);
}

 

posted @ 2016-03-26 20:15  jszyxw  阅读(612)  评论(0编辑  收藏  举报