POJ - 2823 -- Sliding Window

版权声明: https://blog.csdn.net/moon_sky1999/article/details/82284891

题目来源:http://poj.org/problem?id=2823

滑动窗口问题,单调队列入门题。

代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <list>

#define ll long long
#define ull unsigned long long
#define BUG printf("************\n")
using namespace std;

const int maxn = 1e6 + 10;

int n, k;
int a[maxn], q[maxn], p[maxn];

int main() {
    scanf("%d%d", &n, &k);
    for (int i = 1; i <= n; i++)scanf("%d", &a[i]);
    int l = 1, r = 0;
    for (int i = 1; i < k; i++) {
        while (l <= r && q[r] >= a[i])r--;
        r++;
        q[r] = a[i];
        p[r] = i;
    }
    for (int i = k; i <= n; i++) {
        while (l <= r && q[r] >= a[i])r--;
        r++;
        q[r] = a[i];
        p[r] = i;
        if (p[l] <= i - k)l++;
        printf("%d ", q[l]);
    }
    printf("\n");
    l = 1;
    r = 0;
    for (int i = 1; i < k; i++) {
        while (l <= r && q[r] <= a[i])r--;
        r++;
        q[r] = a[i];
        p[r] = i;
    }
    for (int i = k; i <= n; i++) {
        while (l <= r && q[r] <= a[i])r--;
        r++;
        q[r] = a[i];
        p[r] = i;
        if (p[l] <= i - k)l++;
        printf("%d ", q[l]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/moon_sky1999/article/details/82284891