【数据结构】判断出栈顺序合法性

#include      <iostream>
#include       <iomanip>
#include        <string>
#include        <cstdio>
#include         <cmath>
#include       <cstring>
#include     <algorithm>
#include        <vector>
#include         <queue>
#include         <deque>
#include           <map>
#include <unordered_map>
#include           <set>
#include        <bitset>
#include       <fstream>
#include        <time.h>
#include         <stack>

#define               P(n, f) cout<<n<<(f?'\n':' ')
#define                            pi pair<int,int>
#define                                LL long long
#define                      ULL unsigned long long
#define                            lowbit(x) x&(-x)
#define                                mp make_pair
#define                                elif else if
#define       range(i, a, b) for(auto i=a;i<=b;++i)
#define     itrange(i, a, b) for(auto i=a;i!=b;++i)
#define     rerange(i, a, b) for(auto i=a;i>=b;--i)
#define  fill(arr, tmp) memset(arr,tmp,sizeof(arr))
#define IOS ios::sync_with_stdio(false), cin.tie(0)
using namespace std;
template <class T>
class JudgeGirl{
public:
    bool main(vector<T>a,vector<T>b){
        if(a.empty() or b.empty()){
            P("NO",1);
            return false;
        }
        if(a.size()!=b.size()){
            P("NO",1);
            return false;
        }
        stack<T>S;
        int posA=0,posB=0;
        while(posA<a.size()){
            if(S.empty() or S.top()!=b[posB])S.push(a[posA++]);
            else S.pop(),posB++;
        }
        while(!S.empty()){
            if(S.top()!=b[posB++]){
                P("NO",1);
                return false;
            }
            S.pop();
        }
        P("YES",1);
        return true;
    }
};
JudgeGirl<int> A; //可以自己改顺序表的类型
vector<int>a,b; //同上
int n;

int main() {
    cout<<"顺序表长度:";cin>>n;
    range(i,1,n){
        int tmp;
        cin>>tmp;
        a.push_back(tmp);
    }
    range(i,1,n){
        int tmp;
        cin>>tmp;
        b.push_back(tmp);
    }
    A.main(a,b);
    return 0;
}
View Code

暴力栈模拟,时空复杂度:O(n)

posted @ 2018-10-08 15:14  RhythmLian  阅读(894)  评论(0编辑  收藏  举报