【HDU】1022Train Problem I(出栈可行问题)

题目大意:给出一个数(车的数目),两个字符串(前一个为现有车的排序,第二个为要组成的车的排序),

Sample Input

3 123 321

3 123 312

Sample Output

Yes.

in

in

in

out

out

out

FINISH

No.

FINISH

思路:直接用stack模拟栈的顺序:

首先如果出栈序列可行,那么必定存在唯一的可行出栈方式(想想是不是)

我们需要两个指针i,j,用来指定in顺序和out顺序的位置,

如果当前栈顶元素等于out序列中j所指向的那个字符,那么就出栈并且保存com【len++】=“out”;

如果当前的字符出栈不可行时,我们就把in中i所指向的字符加入栈中即可;在判断下一个i;

注意栈操作时:

出栈:栈S不能为空  且  j不能超过出栈序列的最后一个元素 且 S.top() == j所指元素

        入栈:i不能超过入栈序列的最后一个元素

代码:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<stack>
#define maxn 33
using namespace std;

string in;
string out;
string com[maxn];
int n;
int main()
{
    while(cin>>n)
    {
        cin>>in>>out;
        int len=0;
        stack<char>s;
        int i=0,j=0;
        while(i<n&&j<n)
        {
            if(in[i]==out[j]) //相同时,进~出
            {
                com[len++]="in";
                com[len++]="out";
                i++;
                j++;
            }
            else if(s.empty()||(s.top()!=out[j]))//不满足时,进~
            {
                com[len++]="in";
                s.push(in[i]);
                i++;
            }
            else//出~
            {
                com[len++]="out";
                s.pop();
                j++;
            }
        }
        while(!s.empty()&&s.top()==out[j])//判断是否可以出
        {
            com[len++]="out";
            s.pop();
            j++;
        }
        if(s.empty())//栈中无元素时表示恰好可以完成工作,把保存的路径输出即可
        {
            cout<<"Yes."<<endl;
            for(int i=0;i<len;i++)
                cout<<com[i]<<endl;
            cout<<"FINISH"<<endl;
        }
        else
        {
            cout<<"No."<<endl;
            cout<<"FINISH"<<endl;
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值