题解 | #单调栈结构#

单调栈结构

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;
}
全部评论

相关推荐

不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务