0
点赞
收藏
分享

微信扫一扫

第43期:数据结构-单调栈

西曲风 2022-03-11 阅读 97
数据结构

参考:

单调栈 - OI Wiki

1. P5788 【模板】单调栈

#include<bits/stdc++.h>
#include<stack>
using namespace std;
const int maxn=3e6+5;
int read(){
	int x=0,f=1;char c=getchar();
	while(c>'9'||c<'0'){if(c=='-')f=-1;c=getchar();}
	while(c<='9'&&c>='0'){x=x*10+c-'0';c=getchar();}
	return x*f;
}
int n,a[maxn],f[maxn];//a是需要判断的数组(即输入的数组),f是存储答案的数组
stack<int> s;//模拟用的栈 
int main(){
	n=read();
	for(int i=1;i<=n;i++) a[i]=read();
	for(int i=n;i>=1;i--){
		while(s.size()&&a[s.top()]<=a[i]) s.pop();//弹出栈顶比当前数小的
		f[i]=s.empty()?0:s.top();//存储答案,由于没有比她大的要输出0,所以加了个三目运算
		s.push(i);//压入当前元素 
	} 
	for(int i=1;i<=n;i++) cout<<f[i]<<" ";
	cout<<endl; 
	return 0;
} 
举报

相关推荐

0 条评论