栈和排序(思维)

LINK

题目

在这里插入图片描述

思路:

先从后往前找到此时的最大值,存入数组b中
然后从前往后遍历,
当此时i位置的值为最大值时入栈,入栈后还需要比较此时辅助栈中的数值和下一个遍历到的位置的b[i+1]中的值的大小比较,若栈顶数值大于b[i+1]就入栈;
若此时i位置的值不为最大值,就将此值存入辅助栈中。

代码:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N=1e6+10;
stack<int>st,c;
int main() {
	int n,x;cin>>n;
	int a[n+10],b[n+10],ans[n+10];
	for(int i=0;i<n;i++)cin>>a[i];
	for(int i=n-1,maxx=0;i>=0;i--){
		maxx=max(maxx,a[i]);
		b[i]=maxx;
	}
	int pos=0;
	for(int i=0;i<n;i++){
		if(a[i]==b[i]){
			ans[pos++]=a[i];
			while(!st.empty()&&st.top()>b[i+1]){
				ans[pos++]=st.top();
				st.pop();
			}
		}else{
			st.push(a[i]);
		}
	}
	while(!st.empty()){
		ans[pos++]=st.top();st.pop();
	}
	for(int i=0;i<n-1;i++){
		cout<<ans[i]<<" ";
	}cout<<ans[n-1];
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值