0分求调

B3614 【模板】栈

Konnyaku_q @ 2024-09-10 21:09:09

#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<cmath>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
long long t,n,top=0,zhan[1100000],a;
string s;
int main()
{
    cin>>t;
    for(int i=1;i<=t;i++)
    {

        cin>>n; 
        for(int j=1;j<=n;j++)
        {
            cin>>s;
            if(s=="push")
            {
                cin>>a;
                zhan[top++]=a;
            }
            else if(s=="pop")
            {
                if(top==0)
                {
                    cout<<"Empty"<<endl;    
                }
                else
                {
                    top--;
                }
             } 
             else if(s=="query")
             {
                if(top==0)
                {
                    cout<<"Anguei!"<<endl;
                 }
                 else
                 {
                    cout<<zhan[top]<<endl;
                 }
             }
             else if(s=="size")
             {
                cout<<top<<endl;
             }
          }
          top=0; 
        }

  return 0;
}

by thluogu @ 2024-09-10 21:23:24

  1. push 时 top++ ,query 时栈顶元素实际上在 zhan[top-1] 的位置.

修改后代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<cmath>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
unsigned long long t,n,top=0,zhan[1100000],a;
string s;
int main()
{
    cin>>t;
    for(int i=1;i<=t;i++)
    {

        cin>>n; 
        for(int j=1;j<=n;j++)
        {
            cin>>s;
            if(s=="push")
            {
                cin>>a;
                zhan[top++]=a;
            }
            else if(s=="pop")
            {
                if(top==0)
                {
                    cout<<"Empty"<<endl;    
                }
                else
                {
                    top--;
                }
             } 
             else if(s=="query")
             {
                if(top==0)
                {
                    cout<<"Anguei!"<<endl;
                 }
                 else
                 {
                    cout<<zhan[top-1]<<endl;
                 }
             }
             else if(s=="size")
             {
                cout<<top<<endl;
             }
          }
          top=0; 
        }

  return 0;
}

by thluogu @ 2024-09-10 21:25:36

@Konnyaku_q


|