单调队列的学习

前天CUG比赛的D题,也就是POJ3250题

http://poj.org/problem?id=3250 正好拿来学习了下单调队列了

#include<cstdio>
#include<cstring>

const int maxn = 100000 + 10;
int maxq[maxn];
int ind[maxn];
int q[maxn];
int n;
int a[maxn];
long long ans = 0;
void calc(){
    int head = 1, tail = 0;
    for(int i = 1; i <= n; i ++){
        while(head <= tail && q[tail] <= a[i])
          tail --;
        tail ++;
        q[tail] = a[i];
        //printf("%d\n", tail);
        ans += (long long )(tail - 1);
    }
}
int main(){
    while(~scanf("%d", &n)){
        for(int i = 1; i <= n; i ++) scanf("%d", a + i);
        calc();
        //for(int i = 0; i <= n; i ++) printf("%d\n", q[i]);
        printf("%lld\n", ans);
    }
    return 0;
}
// 10   9 8 73 4 2 5 2 2 4 5

http://archive.cnblogs.com/a/2249234/ 这篇博客一看就能理解了

其实我理解的就是,出列的情况和普通的不一样

普通队列出列就是队首,而这个是每从从队尾开始比较,一直找到能插入的位置,然后替换该位置元素,并且该元素出列

单调队列,当然就是保持队列的单调性了

原文地址:https://www.cnblogs.com/louzhang/p/2617837.html