火车进站输出路径(HDU1022)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1022

解题报告:

思路:

就是维护好这个栈,只要它不是空,并且头部和ans相同,就一直出栈,直到不满足条件,然后入栈,重复比较。和Poj上一道题一样。

输出路径,记录在path中,出栈就是out,入栈就是in.

#include <stdio.h>
#include <string.h>
#include <stack>

using namespace std;

int ans[1005];
int x[1005];
bool path[1005];

int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        char str[30];

        scanf("%s",str);
        int len = strlen(str);

        for(int i=0;i<len;i++)
            ans[i] = str[i] - '0';

        scanf("%s",str);
        for(int i=0;i<len;i++)
            x[i] = str[i] - '0';

        stack<int> s;
        int k=0;
        int t=0;
        for(int i=0; i<len+1; i++)
        {
            while(!s.empty()&&s.top()==x[k])
            {
                s.pop();
                path[t++] = false ;
                k++;
            }
            s.push(ans[i]);
            path[t++] = true ;
        }
        if(k==n)
        {
            printf("Yes.
");
            for(int i=0; i<2*n; i++)
            {
                if(path[i])
                    printf("in
");
                else printf("out
");
            }
            printf("FINISH
");
        }
        else printf("No.
FINISH
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/TreeDream/p/5701933.html