首页 > 代码库 > HDU 1022 Train Problem I 模拟栈题解
HDU 1022 Train Problem I 模拟栈题解
火车进站,模拟一个栈的操作,额外的栈操作,查看是否能按照规定顺序出栈。
数据量很少,故此题目很容易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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。