HDU 1022(栈模拟;暴力搜索)

题意:根据火车的进队序列,问知否会出现给定的出队序列。

输入:火车数  进队序列  出队序列。

 

用栈模拟:

#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;

char a[12], b[12];
bool inque[24];
bool solve(int l)
{
    stack<int> q;
    int i = 0, j = 0, t = 0;
    while (i < l)
    {
        if (q.empty() || q.top() != b[i])
        {
            inque[t++] = true;
            if (j >= l) return false;
            q.push(a[j++]);
        }
        else
        {
            ++i;
            inque[t++] = false;
            q.pop();
        }
    }
    return true;
}

void output(int n)
{
    for (int i = 0; i < n; ++i)
        if (inque[i]) printf("in\n");
        else printf("out\n");
}

int main()
{
    int l;
    while (scanf("%d", &l) != EOF)
    {
        scanf("%s %s", a, b);
        if (solve(l))
        {
            printf("Yes.\n");
            output(2*l);
            printf("FINISH\n");
        }
        else
        {
            printf("No.\nFINISH\n");
        }
    }
    return 0;
}


暴力搜索:

#include <cstdio>
#include <cstring>

bool status[24];
char result[12];
char sta[12];
char a[12], b[12];

bool dfs(int status_n, int sta_n, int result_n, int sub, const int len)
{
    char tmp[12];
    if (sub == len && sta_n == 0)
    {
        result[result_n] = '\0';
        if (strcmp(result, b) == 0) return true;
        else return false;
    }
    if (sub < len)
    {
        sta[sta_n++] = a[sub++];
        status[status_n++] = true;
        memcpy(tmp, sta, sta_n);
        if (dfs(status_n, sta_n, result_n, sub, len)) return true;
        sta_n--, sub--, status_n--;
        memcpy(sta, tmp, sta_n);
    }
    if (sta_n != 0)
    {
        result[result_n++] = sta[--sta_n];
        status[status_n++] = false;
        memcpy(tmp, sta, sta_n+1);
        if (dfs(status_n, sta_n, result_n, sub, len)) return true;
        memcpy(sta, tmp, sta_n+1);

    }
    return false;
}

void output(int n)
{
    for (int i = 0; i < n; ++i)
        if (status[i]) printf("in\n");
        else printf("out\n");
}


void solve(int l)
{
    if (dfs(0, 0, 0, 0, l))
    {
        printf("Yes.\n");
        output(2*l);
        printf("FINISH\n");
    }
    else
    {
        printf("No.\nFINISH\n");
    }
}

int main()
{
    int l;
    
    while (scanf("%d", &l) != EOF)
    {
        scanf("%s %s", a, b);
        solve(l);
    }
    return 0;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值