题解 | #单调栈结构#
单调栈结构
http://www.nowcoder.com/practice/e3d18ffab9c543da8704ede8da578b55
单调栈,cin会超时
#include <iostream>
#include <stack>
#include <vector>
#include <cstring>
using namespace std;
int main()
{
int n;
vector<int> a, L;
cin >> n;
for (int i = 0; i < n; i++) {
int x;
// cin >> x;
scanf("%d", &x);
a.push_back(x);
}
stack<int> st;
for (int i = 0; i < n; i++) {
while (!st.empty() && a[i] <= a[st.top()]) {
st.pop();
}
if (st.empty()) {
L.push_back(-1);
} else {
L.push_back(st.top());
}
st.push(i);
}
stack<int> st2;
vector<int> R(n);
for (int i = n - 1; i >= 0; i--) {
while (!st2.empty() && a[i] <= a[st2.top()]) {
st2.pop();
}
if (st2.empty()) {
R[i] = -1;
} else {
R[i] = st2.top();
}
st2.push(i);
}
for (int i = 0; i < n; i++) {
// cout << L[i] << " " << R[i] << endl;
printf("%d %d\n", L[i], R[i]);
}
return 0;
}