洛谷 P2866 [USACO06NOV]糟糕的一天Bad Hair Day

嗯...

 

题目链接:https://www.luogu.org/problem/P2866

这道题可以用单调栈来做...

在输入的同时把小于h的出栈,再把h放进去,这样就构成了一个单调递减的栈,

然后查询栈的大小,这样就求出了栈低能看到哪些元素,因为最后只要求总的数量,所以无需分开。

但注意两个细节:

1.&是短路运算符,先看左边再看右边,这道题中while如果反过来写,则会在empty的时候访问栈顶,所以会RE。

2.ans会很大,所以要用long long

 

AC代码:

#include<cstdio>
#include<iostream>
#include<stack>

using namespace std;

int n, h;
long long ans;//
stack <int> s;

int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i++){
        scanf("%d", &h);
        while(!s.empty() && s.top() <= h) s.pop();//
        ans += s.size();
        s.push(h);
    }
    printf("%lld", ans);
    return 0;
}
AC代码
原文地址:https://www.cnblogs.com/New-ljx/p/11247360.html