Monotonous stack - Cattle passenger 25084 Bad Hair Day

Cattle passenger 20806 Bad Hair Day

Title meaning
cow look to the right 1, 2, 3, see the cattle, and cow after unseen cow 5 cow 5.
Each cow seeking can see the number of cattle.

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

Solution: maintaining a monotonically decreasing stack, each of the right section is only required to maximum).

#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;
}

Guess you like

Origin www.cnblogs.com/--zz/p/11242869.html