ACM基地招新大会(单调栈)

题目链接:点击这里

题目大意:
给定一个长度为 n n n 的序列 a 1 , a 2 , . . . , a n a_1,a_2,...,a_n a1,a2,...,an ,对于 a i a_i ai 求序列从 a i a_i ai 开始前面第二个比他大的元素的位置,若不存在这样的位置,则输出 1 1 1

题目分析:
一开始想的是先用单调栈处理出第一个比其大的元素,然后暴力往前找下一个比他大的元素,但是这样复杂度显然很大,会超时。
然后就考虑优化,我们可以在求完答案后顺便记录下答案,当我们查找 a i a_i ai 时,如果 a i ≥ a i − 1 a_i\ge a_{i-1} aiai1 而且两个对应的前面第一个比他们大的元素是同一个时,我们可以直接从 a i − 1 a_{i-1} ai1 的答案开始向前寻找,这个剪枝后的时间复杂度我不太会算,实测这个剪枝可以让超时程序骤降到 23 m s 23ms 23ms

具体细节见代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<stack>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 1e5+5;
const int maxm = 2e3+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
const int base = 4e5;
int n,a[maxn],ans[maxn];
stack<int>st;
int mp[maxn];

int main()
{
	n = read(); a[0] = inf;
	st.push(0);
	for(int i = 1;i <= n;i++)
	{
		a[i] = read();
		while(a[st.top()] <= a[i]) st.pop();
		mp[i] = st.top();
		if(mp[i] == 0)
		{
			puts("1");
			ans[i] = 1;
		}
		else {
			int pos;
			if(a[i] >= a[i-1] && mp[i]==mp[i-1]) pos = ans[i-1]-1;
			else pos = mp[i]-1;
			while(a[pos] <= a[i]) pos --;
			printf("%d\n",pos+1);
			ans[i] = pos+1;
		}
		st.push(i);
	}
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值