zoukankan      html  css  js  c++  java
  • 【数据结构】判断出栈顺序合法性

    #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?'
    ':' ')
    #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)

  • 相关阅读:
    实现随机颜色
    为网站实现一个验证码
    vue.js帐号,密码,邮箱和移动手机号码正则验证
    从网址中截去主机名和参数
    vue.js判断网址参数是否有效
    创建windows service
    vue.js axios call api example
    vue.js mouse over change the image
    jQuery接收url的参数
    ms sql server排序
  • 原文地址:https://www.cnblogs.com/Rhythm-/p/9754537.html
Copyright © 2011-2022 走看看