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)