天梯赛_L2-045 堆宝塔(模拟)

团体程序设计天梯赛

L2-045 堆宝塔

注意取栈顶元素前,判断栈非空,否则可能爆段错误。

#include <bits/stdc++.h>
using namespace std;

int n;
const int N = 1010;
int a[N];
stack<int> aa, bb;
int cnt, maxl = -1;

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i ++) cin >> a[i];
    for(int i = 1; i <= n; i ++){
        int t = a[i];
        
        if(!aa.empty() && !bb.empty() && t >= aa.top() && t <= bb.top()){    // 出成品
            cnt ++;
            int templ = 0;
            while(!aa.empty()){
                aa.pop();
                templ ++;
            }
            if(templ > maxl) maxl = templ;
            while(!bb.empty() && bb.top() > t){
                aa.push(bb.top());
                bb.pop();
            }
            aa.push(t);
        }

        else if(aa.empty()) aa.push(t);
        else if(t < aa.top()) aa.push(t);
        else if(bb.empty()) bb.push(t);
        else if(t > bb.top()) bb.push(t);
    }

    if(!aa.empty()){
        cnt ++;
        int templ = 0;
        while(!aa.empty()){
            aa.pop();
            templ ++;
        }
        if(templ > maxl) maxl = templ;
    }

    if(!bb.empty()){
        cnt ++;
        int templ = 0;
        while(!bb.empty()){
            bb.pop();
            templ ++;
        }
        if(templ > maxl) maxl = templ;
    }

    cout << cnt << ' ' << maxl << '\n';
    return 0;
}