Question 168. Luogu P2866 Monotone Stack-Bad Hair Day S


Question 168. Luogu P2866 Monotone Stack-Bad Hair Day S


1. The topic

insert image description here
insert image description here
insert image description here

2. Problem solving

The question asks you to calculate the sum of the number of tops that each cow can see when the cow looks to the right. According to the meaning of the question, we think, look to the right, that is, as long as the cow on the right is strictly shorter than the current cow, then you can see the top of the cow. If you encounter a cow that does not meet this condition, let the current cow talk to the next one directly. No need to try again. Obviously, this approach requires two cycles, and the efficiency is not high enough. What should I do? Is there a way I can solve the problem with just one loop?
In this way, we might as well think about it from a different angle. Instead of thinking about how many cows on the right can be seen by the current cow, we should think about how many cows on the left can see the current cow, but keep traversing all the previous cows to the right. What if it's over? Hey, we can use the stack to store the previous cow. Thinking further down, what conditions must the cows in the stack meet in order to see the currently traversed cows? Obviously, the height of the cow must be strictly decreased from the bottom of the stack to the top (the cow to the left must be higher, otherwise the cow will be blocked by the cow slightly to the right, so that the current cow cannot be seen), this is the monotonic stack.
Based on the above, every time we traverse to a cow, I will compare the height of the cow with the height of the cow at the top of the stack (the stack has been maintained strictly decreasing from bottom to top). Pop the cow until it is smaller than the top of the stack, then add the number of cows in the stack at this time (the cows can see the current cow) to the total, and the final total is the result

#include <bits/stdc++.h>

using namespace std;

stack<int> s;

int main()
{
    
    
    int N;
    cin>>N;
    long long res=0;
    for(int i=0;i<N;i++)
    {
    
    
        int h;
        scanf("%d",&h);
        while(!s.empty()&&h>=s.top())//栈里头只存有机会看到位于他们右边高度为h的牛的牛顶的牛,也就是说,我的栈序列必须自底向上严格递减
        {
    
    
            s.pop();//淘汰没法看见当前高度h的牛的牛顶的牛
        }
        res+=s.size();//将能看见当前h的牛的牛顶的牛加到总数中
        s.push(h);//将当前高度h的牛入栈
    }
    cout<<res<<endl;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324345597&siteId=291194637