405J1R训练四(T628214 日志分析)

· · 个人记录

错误思路

看不懂题。

正确思路

先定两个变量stack<int> s1;stack<int> s2;再定一个n,输入n再来个while循环,循环中先定一个整数x变量,在输入x,最后来一个if判断和两个else if:

if(x==0){
    int w;
    cin>>w;
    s1.push(w);
    if(s2.empty()){
        s2.push(w);
    }else if(s2.top()<w){
        s2.push(w);
        }else{
        s2.push(s2.top());
    } 
    }else if(x==1){
        s1.pop();
        s2.pop();   
    }else if(x==2){
        if(s1.empty()){
            cout<<0<<endl;
             }else{
                cout<<s2.top()<<endl;
        }
    }

正确代码

#include<bits/stdc++.h>
using namespace std;
stack<int> s1;
stack<int> s2;
int main(){
    int n;
    cin>>n;
    while(n--){
        int x;
        cin>>x;
        if(x==0){
            int w;
            cin>>w;
            s1.push(w);
            if(s2.empty()){
                s2.push(w);
            }else if(s2.top()<w){
                s2.push(w);
            }else{
                s2.push(s2.top());
            } 
        }else if(x==1){
            s1.pop();
            s2.pop();   
        }else if(x==2){
            if(s1.empty()){
                cout<<0<<endl;
            }else{
                cout<<s2.top()<<endl;
            }
        }
    }
    return 0;
}