UVa 514 Rails(栈的应用)

题目链接:

https://cn.vjudge.net/problem/UVA-514

 1 /*
 2 问题
 3 输入猜测出栈顺序,如果可能输出Yes,否则输出No
 4 
 5 解题思路
 6 貌似没有直接可以判定的方法,紫书上给出的方法是在进行一个入栈出栈操作,看是否能够构成原始的入栈序列。 
 7 */ 
 8 #include<cstdio>
 9 #include<stack>
10 
11 using namespace std;
12 int ok(int a[],int n);
13 int main()
14 {
15     freopen("E:\\testin.txt","r",stdin);
16     int a[1100];
17     int n,i,j;
18     stack<int> s;
19     while(scanf("%d",&n) == 1 && n != 0){
20         while(1){
21             for(i=1;i<=n;i++){
22                 scanf("%d",&a[i]);
23                 if(a[1] == 0)
24                     break;
25             }
26             if(a[1] == 0)
27                 break;
28                 
29             int A=1,B=1,ok=0;
30             while(B <= n){
31                 if(A == a[B]){
32                     A++;B++;
33                 }else if(!s.empty() && s.top() == a[B]){
34                     s.pop();
35                     B++;
36                 }else if(A <= n){
37                     s.push(A++);
38                 }else { 
39                     ok=1; 
40                     break;
41                 }
42             }
43             
44             if(ok)
45                 printf("No\n");
46             else
47                 printf("Yes\n");
48         }
49         printf("\n");
50     }
51     return 0;
52 }

猜你喜欢

转载自www.cnblogs.com/wenzhixin/p/9129798.html