zoukankan      html  css  js  c++  java
  • HDU Train Problem I 1022 栈模拟

    题目大意:

    给你一个n 代表有n列 火车,  第一个给你的一个字符串 代表即将进入到轨道上火车的编号顺序, 第二个字符串代表的是 火车出来之后到顺序,

    分析一下就知道这,这个问题就是栈, 先进后出吗, 就是问你这个编号有没有可能出现, 有可能的话输出顺序,没可能直接输出No

    题目分析:

    我们用栈进行模拟, 先判断是否有这种出栈的可能, 假如有这种可能的话我们在模拟 一遍出栈的顺就行了。

    每一次有新元素入栈我们就判断他是否雨 第二个字符串的第一个元素是否相等, 假如一样, 就让次元素出栈。

    代码

     1 #include <iostream>
     2 #include <queue>
     3 #include <cstdio>
     4 #include <cstring>
     5 #include <cstdlib>
     6 #include <stack>
     7 using namespace std;
     8 #define maxn 15
     9 
    10 
    11 bool OK(char str1[], char str2[],int n)//判断是否存在这种出栈的可能
    12 {
    13     stack<char> P;
    14     P.push('#');//因为有元素要删除赋值, 不能为空, 我们让第一个元素为‘#’
    15     char ans;
    16     int i, j;
    17     for(i=0, j=0; i<n; i++)
    18     {
    19         P.push(str1[i]);
    20         ans = P.top();
    21         while(ans == str2[j] )
    22         {
    23             P.pop();
    24             j ++;
    25             ans = P.top();//此处是要赋值判断的, 假如为空的话就无法赋值, 因此我们让第一个元素为‘#’
    26         }
    27     }
    28     if(j == n)
    29         return true;
    30     return false;
    31 }
    32 
    33 void Putt(char str1[], char str2[],int n)
    34 {
    35     stack<char> P;
    36     P.push('#');
    37     for(int i=0, j=0; i<n; i++)
    38     {
    39         P.push(str1[i]);
    40         printf("in
    ");
    41         char ans = P.top();
    42         while(ans == str2[j])
    43         {
    44             P.pop();
    45             printf("out
    ");
    46             j ++;
    47             ans = P.top();
    48         }
    49     }
    50 }
    51 int main()
    52 {
    53     int n;
    54     char str1[maxn], str2[maxn];
    55     while(cin >> n >> str1 >> str2)
    56     {
    57         if(OK(str1, str2, n) )
    58         {
    59             printf("Yes.
    ");
    60             Putt(str1,str2,n);
    61         }
    62         else
    63             printf("No.
    ");
    64 
    65         printf("FINISH
    ");
    66     }
    67     return 0;
    68 }
  • 相关阅读:
    了解 C++ 默默编写并调用的函数
    确保对象在被使用前的初始化
    尽可能使用 const
    尽量多的以 const/enum/inline 替代 #define
    六 GPU 并行优化的几种典型策略
    五 浅谈CPU 并行编程和 GPU 并行编程的区别
    四 GPU 并行编程的存储系统架构
    三 GPU 并行编程的运算架构
    求解线性方程组的三种基本迭代法
    C#基础 特殊集合(栈集合、队列集合、哈希表集合)
  • 原文地址:https://www.cnblogs.com/chenchengxun/p/4086854.html
Copyright © 2011-2022 走看看