您的位置:首页 > 其它

POJ 2823 Sliding Window 单调队列优化DP

2014-09-12 21:33 316 查看
题意:给出一段包括N个数的数列,求出连续的K个数中最大值和最小值。

思路:离线和在线的问题:因为数列是固定的,那在线的线段树的做法会有很多没有必要的操作。所以我们可以直接采用离线的做法。

我们先讨论最小值。

我们用一个单调队列保存可能成为最小值的数的集合。队列的首是实际的最小值。当窗口向后滑动时,一个数加入,存在在队列中且比它大的数将不能再成为最小值,所以将它们踢掉,再加入这个值。

最小值同理。

代码如下:

#include <cstdio>

using namespace std;

template<class T>
inline bool read(T &n){
T x = 0, tmp = 1; char c = getchar();
while ((c < '0' || c > '9') && c != '-' && c != EOF) c = getchar();
if (c == EOF) return false;
if (c == '-') c = getchar(), tmp = -1;
while (c >= '0' && c <= '9') x *= 10, x += (c - '0'), c = getchar();
n = x*tmp;
return true;
}

template <class T>
inline void write(T n) {
if (n < 0) {
putchar('-');
n = -n;
}
int len = 0, data[20];
while (n) {
data[len++] = n % 10;
n /= 10;
}
if (!len) data[len++] = 0;
while (len--) putchar(data[len] + 48);
}

const int MAX = 1000100;

int N,K;

int q[MAX];
int a[MAX];

int main(void)
{
while(read(N)&&read(K)){
for(int i = 0 ; i < N; ++i)
read(a[i]);
int head = 0;
int tail = 0;
for(int i = 0 ; i < K - 1; ++i){
while(head < tail && q[tail-1] > a[i]) tail--;
q[tail++] = a[i];
}
for(int i = K - 1; i < N; ++i){
while(head < tail && q[tail - 1] > a[i]) tail--;
q[tail++] = a[i];
write(q[head]),putchar(i == N-1?'\n':' ');
if(q[head] == a[i - K + 1]) head++;
}
head = tail = 0;
for(int i = 0 ; i < K - 1; ++i){
while(head < tail && q[tail - 1] < a[i]) tail--;
q[tail++] = a[i];
}
for(int i = K - 1; i < N;++i){
while(head < tail && q[tail - 1] < a[i]) tail--;
q[tail++] = a[i];
write(q[head]),putchar(i == N-1?'\n':' ');
if(q[head] == a[i - K + 1]) head++;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: