牛客 NC14893栈和排序 个人题解

原题链接:

登录—专业IT笔试面试备考平台_牛客网

题面:

题目描述

给你一个1->n的排列和一个栈,入栈顺序给定

你要在不打乱入栈顺序的情况下,对数组进行从大到小排序

当无法完全排序时,请输出字典序最大的出栈序列

输入描述:

第一行一个数n
第二行n个数,表示入栈的顺序,用空格隔开,结尾无空格

输出描述:

输出一行n个数表示答案,用空格隔开,结尾无空格

示例1

输入

5
2 1 5 3 4

输出

5 4 3 1 2

说明

2入栈;1入栈;5入栈;5出栈;3入栈;4入栈;4出栈;3出栈;1出栈;2出栈

解题思路:

如果栈顶的数比当前未入栈的数都大,则栈顶这个数该出栈了。

代码(CPP):

#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
typedef unsigned long long ull; 
const int maxn = 1e6 + 10;
const int INF = 0x3fffffff;
const int mod = 1000000007;
int n, a[maxn], Max[maxn];
stack<int> st;

void solve() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }

    for (int i = n; i >= 1; i--) {  // 预处理Max, Max[i]表示i右边最大的数(包括i)
        Max[i] = max(Max[i + 1], a[i]);
    }

    bool first = true;
    for (int i = 1; i <= n; i++) {
        while (st.size() && st.top() > Max[i]) {  // 在将a[i]入栈前,如果栈顶的数字大于后缀最大的,则出栈
            int t = st.top();
            st.pop();
            if (!first)
                cout << " ";
            first = false;
            cout << t;
        }
        st.push(a[i]);  // a[i]入栈
    }

    while (st.size()) {  // 把栈里边剩下的出栈
        cout << " " << st.top();
        st.pop();
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cout << fixed;
    cout.precision(18);

    solve();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值