UVa 514 Rails

  《算法竞赛入门经典》6.1.2的题目,大意是给一个从1到n的递增序列A和一个1到n的排列B,让你判断能否通过栈操作(压入和弹出)把A转化成B。代码如下:

View Code
 1 #include <cstdio>
 2 #include <stack>
 3 using namespace std;
 4 
 5 const int maxn = 1000+10;
 6 stack<int> s;
 7 
 8 int main()
 9 {    
10 #ifdef     LOCAL    
11     freopen("in", "r", stdin);
12 #endif
13     int n;
14     int a[maxn];
15     while(scanf("%d", &n) != EOF && n)
16     {
17         while(true)
18         {
19             scanf("%d", &a[0]);
20             if(a[0] == 0)   
21             {
22                 printf("\n");
23                 break;
24             }
25             for(int i = 1; i < n; i++)   scanf("%d", &a[i]);
26             int p = 1, q = 0;
27             while(!s.empty())   s.pop();
28             while(1)
29             {
30                 if(!s.empty() && s.top() == a[q])
31                 {
32                     s.pop();
33                     q++;
34                 }
35                 else
36                 {
37                     if(p > n)   break;
38                     s.push(p);
39                     p++;
40                 }
41             }
42             if(q >= n)   printf("Yes\n");
43             else   printf("No\n");
44         }
45     }
46     return 0;
47 }
48                 
原文地址:https://www.cnblogs.com/xiaobaibuhei/p/3056806.html