AcWing 830. 单调栈
原题链接
简单
作者:
松鼠爱葡萄
,
2020-08-23 13:25:45
,
所有人可见
,
阅读 785
暴力超时代码
#include<iostream>
using namespace std;
const int N = 1e5 + 10;
int a[N];
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
printf("-1 ");
for (int i = 1; i < n; i++) {
for (int j = i - 1;; j--) {
if (j >= 0 && a[j] < a[i]) {
cout << a[j] << " ";
break;
} else if (j < 0) {
cout << "-1 ";
break;
}
}
}
}
单调栈
#include<iostream>
using namespace std;
const int N = 1e5 + 10;
int stk[N], tt;
int main() {
int n;
cin >> n;
while (n--) {
int x;
scanf("%d", &x);
while (tt && stk[tt] >= x) tt--;
if (!tt) printf("-1 ");
else printf("%d ", stk[tt]);
stk[++tt] = x;
}
}