AOJ 11.Rails

模拟栈

按照目标一个一个试着移动即可

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <string>
 6 #include <iostream>
 7 #include <vector>
 8 #include <list>
 9 #include <stack>
10 using namespace std;
11 
12 #define REP(n) for(int o=0;o<n;o++)
13 
14 const int maxn = 1005;
15 
16 bool Do() {
17     int n;
18     int a[maxn];
19     scanf("%d",&n);
20     if(n == 0)
21         return false;
22     while(scanf("%d",&a[0]),a[0] != 0) {
23         REP(n - 1)
24             scanf("%d",&a[o + 1]);
25         stack<int> S,A;
26         REP(n)
27             A.push(n - o);
28 
29         bool ok = true;
30         //尝试将编号i+1出站
31         for(int i = 0;i < n;i++) {
32             //从中转站出站
33                 /*
34                 while的原理
35                 如果中转站中的车符合要求,让它出站,结束该次循环·····1
36                 如果中转站最外面的车不符合要求,检查A口,将它进站,继续上一步·····2
37                 如果A口已经没有车,则无解·····3
38                 */
39             while(1) {
40                 if(!S.empty()&&S.top() == a[i]) {//·····1
41                     S.pop();
42                     break;
43                 } else {//·····3
44                     if(A.empty()) {
45                         ok = false;
46                         break;
47                     } else {//·····2
48                         S.push(A.top());
49                         A.pop();
50                     }
51                 }
52             }
53             //不能达到题目的要求
54             if(!ok)
55                 break;
56         }
57         printf("%s",ok ? "Yes
" : "No
");
58     }
59     printf("
");
60     return true;
61 }
62 
63 int main() {
64     while(Do());
65     return 0;
66 }
原文地址:https://www.cnblogs.com/ohyee/p/5258693.html