單調棧-牛客 25084 Bad Hair Day

牛客 20806 Bad Hair Dayios

題目意思
牛1向右看,看得見 牛2,3,4, 看不見 牛5 以及 牛5以後的牛。
求每一個牛能看見牛的個數。spa

1 2 3 4 5 6
O O
OO O
OOO O
OOOOOOcode

題解:維護一個單調遞減棧,只要求每一個最大值的右區間便可)。ci

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

typedef long long int ll;

const int MAXN = 8e4 + 3;

using namespace std;

ll height[MAXN];

int main(){
    int N;
    ll ans = 0;
    cin >> N;
    for(int i=0;i<N;i++) cin >> height[i];
    height[N] = 1e10;
    stack<int> s;
    for(int i=0;i<=N;i++){
        while(!s.empty()&&height[s.top()] <= height[i]){
            ans += (i-s.top()-1);
            s.pop();
        }
        s.push(i);
    }
    cout << ans << endl;
    return 0;
}
相關文章
相關標籤/搜索