码迷,mamicode.com
首页 > 其他好文 > 详细

例题6-2(Rails, UVa 514)

时间:2018-01-30 21:20:43      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:img   顺序   iostream   数组   src   stack   存储   for   none   

题目链接

       给定入栈顺序,问能否以给出的顺序出栈。

       众所周知,栈的特点是先入后出。

       此特点在该题中体现为对于当前需要出栈的元素(要想先出),必须位于栈顶或者还未入栈(必须后入)。

       用数组target来存储出栈序列,target[B_now] 表示当前需要驶入B的车厢(即当前需要出栈的元素),A_first表示当前A中第一个车厢(即下一个入栈元素)

技术分享图片
 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 
 5 const int MAX_N = 1000 + 10;
 6 
 7 int main() {
 8     int N, target[MAX_N];
 9     
10     while(cin >> N && N != 0) {//多个block的循环 
11         while(true) {//多个序列的循环 
12             cin >> target[0];
13             if(target[0] == 0) break; 
14             for(int i=1; i<N; i++)  cin >> target[i];
15             stack<int> s;
16             int A_first = 1, B_now = 0;  //设A中第一个元素为A_first,当前驶入B的元素为B_now 
17             for(; B_now<N; B_now++) {
18                 while( (s.empty() || s.top() != target[B_now]) && A_first <= N) {/*如果栈空或栈顶元素不为target[B_now]
19                 且A中还有元素,从A中入栈 */
20                     s.push(A_first); A_first++;
21                 }
22                 if(s.top() == target[B_now]) s.pop();
23                 else { cout << "No" << endl; break; }
24             }
25             if(B_now == N) cout << "Yes" << endl; 
26         }
27         cout << endl;
28     }
29     return 0;
30 }
My Code

       下面给出书上给出的代码(注:书上的代码并不适应oj上的输入模式,故直接提交结果为WA)

技术分享图片
 1 // UVa514 Rails
 2 // Rujia Liu
 3 #include<cstdio>
 4 #include<stack>
 5 using namespace std;
 6 const int MAXN = 1000 + 10;
 7 
 8 int n, target[MAXN];
 9 
10 int main() {
11   while(scanf("%d", &n) == 1) {
12     stack<int> s;
13     int A = 1, B = 1;
14     for(int i = 1; i <= n; i++)
15       scanf("%d", &target[i]);
16     int ok = 1;
17     while(B <= n) {
18       if(A == target[B]){ A++; B++; }
19       else if(!s.empty() && s.top() == target[B]){ s.pop(); B++; }
20       else if(A <= n) s.push(A++);
21       else { ok = 0; break; }
22     }
23     printf("%s\n", ok ? "Yes" : "No");
24   }
25   return 0;
26 }
View Code

 

例题6-2(Rails, UVa 514)

标签:img   顺序   iostream   数组   src   stack   存储   for   none   

原文地址:https://www.cnblogs.com/c138Rick/p/8372749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!