洛谷 P5788 【模板】单调栈

 题目链接:

P5788 【模板】单调栈 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)icon-default.png?t=M666https://www.luogu.com.cn/problem/P5788

题目描述 :

找个数列中每一个元素右边第一个比本身大的那个数,输出其下标。找不到则输出0;

思路:

可以用单调栈来实现。

手动模拟一个单调递减的栈,栈存储的是下标,若栈不为空,则栈顶元素便是我们想要的那个数的下标。

while (!st.empty() && a[i] >= a[st.top()])st.pop();
		if (!st.empty()) ans.push_back(st.top());
		else ans.push_back(0);
		st.push(i);

由于题目要求的是找右边的元素,那么从头遍历数组的方法显然是不行的,因此我们需要从末尾遍历整个数组。

注意将得到的结果存储到另一个数组里面,再倒序输出即可。

AC代码:

#include <bits/stdc++.h>

using namespace std;

stack<int> st;
int const N = 3000010;
int a[N];
vector<int > ans;

int main()
{
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	for (int i = n; i >= 1; i--)
	{
		while (!st.empty() && a[i] >= a[st.top()])st.pop();
		if (!st.empty()) ans.push_back(st.top());
		else ans.push_back(0);
		st.push(i);
	}
	for (int i = ans.size() - 1; i >= 0; i--) cout << ans[i] << ' ';
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值