【单调栈】数据结构实验之栈与队列六:下一较大值(二)

Think:
1知识点:单调栈
2题意:输入一个序列(1<=n<=100000),输出序列中当前数以及序列中大于这个数的第一个数,
3解题思路:数据量较大,暴力会超时,可通过维护一个单调栈
第一步:若栈为空或者栈顶大于等于当前元素,当前元素进栈
第二步:若栈不为空且栈顶小于当前元素,栈顶出栈
第三步:重复第一步和第二步,直至所有元素处理完成
4反思:
(1):数组开小了导致超时错误-why不是数组越界呢?

以下为Accepted代码

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int max_size = 100414;

struct Node{
    int x, id;
};

class stack{
private:
    int size;
    Node sta[max_size];
public:
    stack(){size = 0;}
    void push(Node x);
    Node top();
    void pop();
    bool empty();
};

void stack::push(Node x){
    sta[size++] = x;
}
Node stack::top(){
    return sta[size-1];
}
void stack::pop(){
    size--;
}
bool stack::empty(){
    return size == 0;
}

int rec[max_size];
int book[max_size];

int main(){
    int T, n, i;
    Node t1, t2;
    scanf("%d", &T);
    while(T--){
        stack s1;

        scanf("%d", &n);
        for(i = 1; i <= n; i++){
            scanf("%d", &rec[i]);
            t1.x = rec[i], t1.id = i;
            while(!s1.empty()){
                t2 = s1.top();
                if(t2.x < t1.x){
                    s1.pop();
                    book[t2.id] = t1.x;
                }
                else break;
            }
            s1.push(t1);
        }
        while(!s1.empty()){
            t2 = s1.top();
            s1.pop();
            book[t2.id] = -1;
        }
        for(i = 1; i <= n; i++){
            printf("%d-->%d\n", rec[i], book[i]);
        }
        if(T) printf("\n");
    }
    return 0;
}


/***************************************************
User name: 
Result: Accepted
Take time: 88ms
Take Memory: 1752KB
Submit time: 2017-10-04 10:37:33
****************************************************/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值