【POJ3250】Bad Hair Day 单调栈

题目大意:给定一个由 N 个数组成的序列,求以每个序列为基准,向右最大有多少个数字都比它小。

单调栈

  1. 单调栈中维护的是数组的下标。
  2. 单调栈在每个元素出栈时统计该出栈元素的答案贡献或对应的值。
  3. 单调栈主要应用于区间最值的贡献问题。

代码如下

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn=8e4+10;
const int inf=0x3f3f3f3f;

inline int read(){
	int x=0,f=1;char ch;
	do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch));
	do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch));
	return f*x;
}

int n,h[maxn],stk[maxn],top;
long long ans;

void read_and_parse(){
	n=read();
	for(int i=1;i<=n;i++)h[i]=read();
	h[n+1]=inf;
}

void solve(){
	for(int i=1;i<=n+1;i++){
		if(!top||h[i]<h[stk[top]])stk[++top]=i;
		else{
			while(top&&h[i]>=h[stk[top]])ans+=i-stk[top--]-1;
			stk[++top]=i;
		}
	}
	printf("%lld
",ans);
}

int main(){
	read_and_parse();
	solve();
	return 0;
} 
原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10065163.html