题解 | #单调栈结构#

单调栈结构

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

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 12:02
ssob上原来真有BOSS啊
硫蛋蛋:这种也是打工的,只不是是给写字楼房东打工
点赞 评论 收藏
分享
风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
双非有机会进大厂吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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