Train Problem I(模拟栈)

题意:模拟栈,试问使用2个栈,能否使得串1变为串2

思路:模拟,经典问题,注意只要相同的元素放到栈顶后就不会再移动了,只需要考虑剩下的元素,因此每次只考虑一个元素的进入方式。

#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
int n,pd[200005];
char s1[200005],s2[200005],s3[200005];
int main(){
    while (scanf("%d %s %s",&n,s1,s2)!=EOF){
        int t1=0,t2=0,i=1,cnt=0;s3[i]=s1[0];pd[0]=1;
        while (t1<n&&t2<n){
            if (s3[i]==s2[t2]){
                i--;cnt++;pd[cnt]=0;t2++;
            }else{
                s3[++i]=s1[++t1];cnt++;pd[cnt]=1;
            }
        }
        if (i==0){
            printf("Yes.
");
            for (int i=0;i<=cnt;i++)
                if (pd[i]==0) printf("out
");else printf("in
");
        }else printf("No.
");
        printf("FINISH
");
    }
}
原文地址:https://www.cnblogs.com/qzqzgfy/p/5609355.html