Poj 3250 bad hair day (monotonous stack)

Source: Internet
Author: User

Address: poj 3250

Monotonous stack for beginners. Multiple schools and online competitions have already met each other twice.

The monotonous stack principle is simple and cannot be simple .. It is to make the elements in the stack monotonically from the top of the stack to the bottom of the stack.

For example, incremental and monotonous stacks.

If the number at the top of the stack is smaller than the number at the top of the stack, pop the number at the top of the stack to keep the monotonicity in the stack.

For this question, we will traverse from right to left and create an incremental monotonous stack. So each POP is the number of cows that can be seen by the current ox. Then accumulate.

The Code is as follows:

#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <stdlib.h>#include <math.h>#include <ctype.h>#include <queue>#include <map>#include <set>#include <algorithm>#include <stack>using namespace std;#define LL long longLL a[100000], dp[100000];stack<int>q;int main(){    int n, i, j;    LL sum=0;    scanf("%d",&n);    for(i=0;i<n;i++)    {        scanf("%lld",&a[i]);    }    memset(dp,0,sizeof(dp));    for(i=n-1;i>=0;i--)    {        dp[i]=1;        while(!q.empty()&&a[q.top()]<a[i])        {            dp[i]+=dp[q.top()];            sum+=dp[q.top()];            q.pop();        }        q.push(i);    }    /*for(i=0;i<n;i++)    {        printf("%d ",dp[i]);    }*/    printf("%lld\n",sum);    return 0;}


Poj 3250 bad hair day (monotonous stack)

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.