题目一:
给定一个长度为 N 的整数数列,输出每个数左边第一个比它小的数,如果不存在则输出 −1。
输入格式
第一行包含整数 N,表示数列长度。
第二行包含 N 个整数,表示整数数列。
输出格式
共一行,包含 N 个整数,其中第 i 个数表示第 i 个数的左边第一个比它小的数,如果不存在则输出 −1。
数据范围
1 ≤ N ≤ 105
1 ≤ 数列中元素 ≤ 109
输入样例:
5
3 4 2 7 5
输出样例:
-1 3 -1 2 2
原题链接:https://www.acwing.com/problem/content/832/
#include<iostream>
using namespace std;
const int N = 100010;
int q[N], tt;
int main()
{
int m;
cin >> m;
while(m --)
{
int x;
cin >> x;
while(tt && q[tt] >= x) tt--;//在栈顶前面的数字可能比x还要大,所以要一直删
if(!tt) cout << "-1 ";
else cout << q[tt] << " ";
q[++ tt] = x;//注意细节:++ tt
}
return 0;
}
题目二:
原题链接:https://www.luogu.com.cn/problem/P5788
#include<iostream>
#include<stack>
using namespace std;
const int N = 1e7 + 10;
int a[N], ans[N];
int main()
{
stack<int>st;
int x;
int n;
cin >> n;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = n; i >= 1; i--)
{
while (!st.empty() && a[st.top()] <=a[i]) st.pop();
if (!st.empty())ans[i] = st.top();
else ans[i] = 0;
st.push(i);
}
for (int i = 1; i <= n; i++) printf("%d ", ans[i]);
return 0;
}