题目链接:点击这里
题目大意:
给定一个长度为
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}
ai≥ai−1 而且两个对应的前面第一个比他们大的元素是同一个时,我们可以直接从
a
i
−
1
a_{i-1}
ai−1 的答案开始向前寻找,这个剪枝后的时间复杂度我不太会算,实测这个剪枝可以让超时程序骤降到
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;
}