题意:根据火车的进队序列,问知否会出现给定的出队序列。
输入:火车数 进队序列 出队序列。
用栈模拟:
#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;
}