7-2 堆棧操作合法性 (20 分)


輸入格式:

輸入第一行給出兩個正整數N和M,其中N是待測序列的個數,M(≤50)是堆棧的最大容量。隨后N行,每行中給出一個僅由SX構成的序列。序列保證不為空,且長度不超過100。

輸出格式:

對每個序列,在一行中輸出YES如果該序列是合法的堆棧操作序列,或NO如果不是。

輸入樣例:

4 10
SSSXXSXXSX
SSSXXSXXS
SSSSSSSSSSXSSXXXXXXXXXXX
SSSXXSXXX

輸出樣例:

YES
NO
NO
NO

代碼:

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <string>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define LIST_INIT_SIZE 100000
#define LISTINCREMENT 10
#define mod 256
#define SElemType char
#define lowbit(x) (x&(-x))
#define mem(a,b) memset(a,b,sizeof(a))
#define FRER() freopen("in.txt","r",stdin);
#define FREW() freopen("out.txt","w",stdout);
using namespace std;
typedef struct{
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;
void InitStack(SqStack&S,int m){
    S.stacksize = m;
    S.base = (SElemType*)malloc(S.stacksize*sizeof(SElemType));
    S.top = S.base;
}
int SPush(SqStack&S){
    if(S.top-S.base>=S.stacksize) return 0;
    S.top++;
    return 1;
}
int Pop(SqStack&S){
//    cout<<*S.top<<" "<<*S.base<<endl;
    if(S.top==S.base) return 0;
    --S.top;
    return 1;
}
bool isRight(char *s,int m){
    SqStack S;
    InitStack(S, m);
    bool flag = true;
    int i;
    for(i=0;s[i];i++){
        if(s[i]=='S'){
            if(!SPush(S)){
                flag = false;
                break;
            }
        }else{
            if(!Pop(S)){
                flag = false;
                break;
            }
        }
    }
    if(S.top!=S.base) return false;
    if(s[i]!='\0') return  false;
    return  true;
}
int main(){
    int T;
    int m;
    scanf("%d%d",&T,&m);
    while(T--){
        char s[1000];
        scanf("%s",s);
        if(isRight(s,m)) printf("YES\n");
        else printf("NO\n");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM