题解 | #单调栈结构#

单调栈结构

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

相关推荐

头像
04-17 09:29
已编辑
湖南农业大学 后端
睡姿决定发型丫:本硕末9也是0offer,简历挂了挺多,只有淘天 美团 中兴给了面试机会,淘天二面挂,美团一面kpi面,中兴一面感觉也大概率kpi(虽然国企,但一面0技术纯聊天有点离谱吧)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务