机试练习03:hdu1022——铁轨问题

一、题目

二、题解思路

先入先出,用栈实现。

用一个int数组result存储是结果,是出栈还是进栈。

判断栈顶元素和输出队列第一个元素是否一致,一致,则出栈;不一致,则把输入队列下一个元素压栈。

当所有输入队列的元素都已经压入栈中,还未按输出队列出栈时,则无法输出,打印“No.”;否则,打印所有结果。

三、题解代码

 1 #include <iostream>
 2 #include "stdio.h"
 3 #include "stdlib.h"
 4 #include <stack>
 5 
 6 #define MAX 100
 7 
 8 using namespace std;
 9 
10 int main()
11 {
12     stack<char> s;
13     int n, i, j, k;
14     int result[MAX];
15     char in[MAX], out[MAX];
16     while(cin >> n >> in >> out)
17     {
18         i = 0, j = 0, k = 1;
19         s.push(in[0]);
20         result[0] = 1;
21         
22         while(i < n && j < n)
23         {
24             if(s.size() && s.top() == out[j])
25             {
26                 s.pop();
27                 j++;
28                 result[k++] = 0;
29             }
30             else
31             {
32                 if(i==n)
33                     break;
34                 s.push(in[++i]);
35                 result[k++] = 1;
36             }
37         }
38         if(i == n)
39             cout<<"No."<<endl;
40         else
41         {
42             cout<<"Yes."<<endl;
43             for(i=0; i<k; i++)
44                 if(result[i])
45                     cout<<"in"<<endl;
46                 else
47                     cout<<"out"<<endl;
48         }
49         cout<<"FINISH"<<endl;
50     }
51     return 0;
52 }

 

posted @ 2018-04-09 17:45  Alyssa_young  阅读(207)  评论(0编辑  收藏  举报