20分WA+TLE求助

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

qfpjm @ 2021-08-14 10:05:37

#include <bits/stdc++.h>

using namespace std;

int T;

int main()
{
    cin >> T;
    while (T --)
    {
        int n, a[100005], top = 1;
        stack<int> stk;
        bool is_true = false;
        cin >> n;
        for (int i = 1 ; i <= n ; i ++)
        {
            cin >> a[i];
        }
        for (int i = 1 ; i <= n ; i ++)
        {
            int x;
            cin >> x;
            bool flag = false;
            int new_top = 0;
            for (int j = top ; j <= n ; j ++)
            {
                if (a[j] == x)
                {
                    flag = true;
                    new_top = j;
                    break;
                }
            }
            if (flag)
            {
                for (int j = top ; j <= new_top ; j ++)
                {
                    stk.push(a[j]);
                }
                stk.pop();
                top = new_top;
            }
            else
            {
                if (stk.top() != x)
                {
                    is_true = true;
                }
                else
                {
                    stk.pop();
                }
            }
        }
        if (!is_true)
        {
            cout << "Yes" << endl;
        }
        else
        {
            cout << "No" << endl;
        }
    }
    return 0;
}

|