1 条题解
-
1
维护一个单调递增的栈,如果当前数字小于等于栈顶元素,则一直出栈,直到栈顶元素小于当前元素,此时栈顶元素即为当前元素左侧第一个比他小的元素。 当然,如果栈为空,根据题意输出 。
存值
#include <iostream> using namespace std; const int N = 100010; int a[N]; int s[N]; int n, top; int main() { cin >> n; for(int i = 1; i <= n; ++ i) cin >> a[i]; for(int i = 1; i <= n; ++ i) { while(top && s[top] >= a[i]) -- top; if(top) cout << s[top] << ' '; else cout << -1 << ' '; s[++ top] = a[i]; } return 0; }
存下标
#include <iostream> using namespace std; const int N = 100010; int a[N]; int s[N]; int n, top; int main() { cin >> n; for(int i = 1; i <= n; ++ i) cin >> a[i]; for(int i = 1; i <= n; ++ i) { while(top && a[s[top]] >= a[i]) -- top; if(top) cout << a[s[top]] << ' '; else cout << -1 << ' '; s[++ top] = i; } return 0; }
- 1
信息
- ID
- 5521
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 9
- 标签
- 递交数
- 12
- 已通过
- 5
- 上传者