HDU 1022 train problem I simulated stack question

Source: Internet
Author: User

The train enters the station, simulates a stack operation, and performs additional stack operations to check whether the stack can be output in the specified order.

The data volume is small, so the question is easy to AC.

Directly use Arrays for simulation.


#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 ini++;//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 backint k = 0;//check possiblefor (; 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;}

Solution 2:

#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 ini++;//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;}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.