题目大意:有一列火车,给出车厢数和车厢的序列,目标序列,通过一个类似栈的车轨,能不能变成目标序列,能得话输出方案。
解题思路:虽说有一种遍历的方式可以判断,即当目标序列存在a,b,c这样的序列时,若f(a) > f(c) > f(b)时即为不可变为的序列,(f(i)代表第i个元素在原序列中的出现的顺序),但对与本体我觉得不合适,首先原数列是不定的,所以判断优先级的时候比较麻烦,而且如果可能转化的时候要输出路径。。。。所以还是选择用栈直接模拟吧。
#include#include #include using namespace std; const int N = 1005; int n, cnt, rec[N]; char str[N], tmp[N]; bool judge() { stack s; int i = 0, j = 0; while (1) { if (i < n && (s.empty() || s.top() != tmp[j])) { s.push(str[i]); rec[cnt++] = 1; i++; } else if (s.top() == tmp[j]) { s.pop(); cnt++; j++; } else return false; if (j == n) return true; } } int main () { while (scanf("%d%s%s", &n, str, tmp) == 3) { cnt = 0; memset(rec, 0, sizeof(rec)); if (judge()) { printf("Yes.\n"); for (int i = 0; i < cnt; i++) printf("%s\n", rec[i] "in" : "out"); } else printf("No.\n"); printf("FINISH\n"); } return 0; }