为什么会有runtime error,还有不对的

P4387 【深基15.习9】验证栈序列

data740 @ 2024-09-10 21:15:34

#include<iostream>
#include<stack>
using namespace std;

stack<int>n;
int pushed[100005];
int poped[100005];

int main()
{
    int cnt;
    cin >> cnt;
    while (cnt--)
    { 
        int i = 0, j = 0;
        int num;
        cin >> num;
        int tmp = num;
        while (num--)
        {
            cin >> pushed[i++];
        }
        num = tmp;
        while (num--)
        {
            cin >> poped[j++];
        }
        num = tmp;
        int now = 1;
        n.push(pushed[0]);
        for (int i = 0; i < num; i++)
        {
            while (poped[i] != n.top() && now < num)
            {
                n.push(pushed[now++]);
            }
            if (poped[i] == n.top())n.pop();
            else
            {
                cout << "No" << endl;
                return 0;
            }
        }
        cout << "Yes" << endl;
    }
}

by feizhu_QWQ @ 2024-09-10 21:41:53

@data740
我来揪一下你的错:

  1. 在判断可以出栈的时候,不能只用if,需要改成while出栈
  2. 你在poped[i] == n.top()的时候不能这样建议的判断,你需要另一个变量,来判断当前遍历出栈序列到第几个了

如果改不出来可以参考我的代码:

#include<bits/stdc++.h>
using namespace std;
int pushed[1000005],poped[1000005];
int a[1000005];
int top=0;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        top=0;
        int q=1;
        for(int i=1;i<=n;i++) cin>>pushed[i];
        for(int i=1;i<=n;i++) cin>>poped[i];
        for(int i=1;i<=n;i++)
        {
            a[++top]=pushed[i];
            while(a[top]==poped[q]&&q<=n&&top>0)
            {
                q++;
                top--;
            }
        }
        if(q==n+1)
        {
            cout<<"Yes"<<endl;
        }
        else
        {
            cout<<"No"<<endl;
        }
    }
    return 0;
}

by data740 @ 2024-09-11 10:44:34

懂了,感谢


|