火车进站,模拟一个栈的操作,额外的栈操作,查看是否能按照规定顺序出栈。
数据量很少,故此题目很容易AC。
直接使用数组模拟就好。
#include <stdio.h> const int MAX_N = 10; char inOrder[MAX_N], outOrder[MAX_N], stk[MAX_N]; bool rs[MAX_N<<2]; int n; int main() { while (scanf("%d", &n) != EOF) { scanf("%s %s", inOrder, outOrder); int j = 0, out = 0, i = 0, st = 0; bool possible = true; while (possible && !(st == 0 && out == n)) { for (; i < n && inOrder[i] != outOrder[out]; i++) { rs[j++] = true; stk[st++] = inOrder[i]; }//push in i++;//Watch out: don't forget while inOrder[i]==outOrder[out]! rs[j++] = true; rs[j++] = false; out++; while (st > 0 && stk[st-1] == outOrder[out]) { st--; out++; rs[j++] = false; }//pop back int k = 0;//check possible for (; k < st && stk[k] != outOrder[out]; k++); if (k < st) possible = false; } if (possible) { puts("Yes."); for (int i = 0; i < j; i++) { if (rs[i]) puts("in"); else puts("out"); } } else puts("No."); puts("FINISH"); } return 0; }
解法二:
#include <stdio.h> const int MAX_N = 10; char inOrder[MAX_N], outOrder[MAX_N], stk[MAX_N]; bool rs[MAX_N<<2]; int n; int main() { while (scanf("%d", &n) != EOF) { scanf("%s %s", inOrder, outOrder); int j = 0, out = 0, i = 0, st = 0; while (i<n && !(st == 0 && out == n)) { for (; i < n && inOrder[i] != outOrder[out]; i++) { rs[j++] = true; stk[st++] = inOrder[i]; }//push in i++;//Watch out: don't forget while inOrder[i]==outOrder[out]! rs[j++] = true; rs[j++] = false; out++; while (st > 0 && stk[st-1] == outOrder[out]) { st--; out++; rs[j++] = false; }//pop back } if (st == 0 && out == n) { puts("Yes."); for (int i = 0; i < j; i++) { if (rs[i]) puts("in"); else puts("out"); } } else puts("No."); puts("FINISH"); } return 0; }
HDU 1022 Train Problem I 模拟栈题解
时间: 2024-12-20 13:33:48