POJ3250 cow's field of vision (monotone stack)

Source: Internet
Author: User
A group of highly different cows from left to right stand in a row, each cow can only see its right side of the shorter cow hairstyle, if you encounter a height greater than or equal to its cattle, you can not continue to see the cow and the other back of the cow hairstyle.
The height of these cows is given, and the number of cows per cow can be seen.
Idea: Calculate the number of cows that can be seen per cow, which can be equivalent to the number of times each cow can be seen

From left to right to read the current cattle height, starting from the top of the stack is less than or equal to the current height of the cattle to remove those elements, the number of elements remaining in the stack is to see the current cattle of the number of other cows, summation is the answer.

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
# Include <stack>
#include <string>
#include <cmath>
#include <cstdio>
# Include <functional>//Kengen There is a header file
typedef long long ll;
#define N 1005
using namespace std;

int main ()
{
    int n;
    while (scanf ("%d", &n) ==1) {
        int num;
        ll sum=0;
        scanf ("%d", &num);
        stack<int>s;
        while (!s.empty ())
            s.pop ();
        S.push (num);
        for (int i=1;i<n;i++) {
            scanf ("%d", &num);
            while (!s.empty () &&num>=s.top ())//current cow is less than the stack top
                s.pop ();
            Sum+=s.size ();
            S.push (num);
        }
        printf ("%lld\n", sum);
    }
    return 0;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.