HDU 1022 Train Problem I 用栈瞎搞

题目大意:有n辆火车,按一定的顺序进站(第一个字符串顺序),问是否能按规定的顺序出站(按第二个字符串的顺序出去),如果能输出每辆火车进出站的过程。

题目思路:栈的特点是先进后出,和题意类似,还有有一种情况是:开进来立马有开出去。并用vis[]数组的0,1标记进出站情况。

具体看代码

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
#include<iostream>
#define MAX 100005
using namespace std;

int main()
{
    int A,B,top,i,j,n,vis[MAX],stack[MAX],ok;
    char str1[MAX],str2[MAX];
    while(scanf("%d%s%s",&n,str1,str2)!=EOF)
    {
        ok=1;
        memset(vis,0,sizeof(vis));
        i=0;
        A=0;//当前str1的位置
        B=0;//当前str2的位置
        top=0;//栈顶
        while(B<n)
        {
            if(str2[B]==str1[A])//如果两者相同就是即进即出的情况
            {
                vis[i++]=1;//进站
                vis[i++]=0;//出站
                A++;
                B++;
            }

            else if(top && stack[top]==str2[B])//如果栈非空,而且栈顶元素=str2当前元素则弹出栈
            {
                vis[i++]=0;
                top--;
                B++;
            }

            else if(A <= n)
            {
                stack[++top]=str1[A++];//压入栈
                vis[i++]=1;
            }

            else
            {
                ok=0;
                break;
            }
        }

        if(!ok)
        {
            printf("No.\nFINISH\n");
        }

        else
        {
            printf("Yes.\n");
            for(j=0;j<i;j++)
            {
                if(vis[j])
                    printf("in\n");
                else
                    printf("out\n");
            }
            printf("FINISH\n");
        }
    }
    return 0;
}
View Code

 

posted @ 2016-08-17 00:03  声声醉如兰  阅读(139)  评论(0编辑  收藏  举报