栈 铁轨

每辆火车都从A方向驶入车站,再从B方向驶出车站,同时它的车厢可以进行某种形式的重新组合。假设从A方向驶来的火车有n节车厢(n<1000),分别按顺序编号为1,2,...,n。假定在进入车站之前每节车厢之间都是不连着的,并且它们可以自行移动,直到处在B方向的铁轨上。另外假定车站C里可以停放任意多节的车厢。但是一旦当一节车厢进入车站C,它就不能再回到A方向的铁轨上了,并且一旦当它进入B方向的铁轨后,它就不能再回到车站C。负责车厢调度的工作人员需要知道能否使它以a1,a2,...,an的顺序从B方向驶出。
    请写一个程序,用来判断能否得到指定的车厢顺序。

【输入格式】

    输入由两行组成:

第一行有n(n<1000),表示有n节车厢。

第二行n个数表示一组需判定的车厢。

【输出格式】

    对于每个输入输出有一行,每行根据判断,如果能正常驶出输出"YES",否则输出"NO"。

【输入输出样例】

5

5 4 3 2 1

Yes

5

5 4 1 2 3

No

6

6 5 4 3 2 1

Yes

#include<stdio.h>
const int MAXN = 1000+10;
int n,target[MAXN];
int main()
{
    while(scanf("%d",&n)==1)
    {
        int stack[MAXN],top=0;
        int A=1,B=1;
        for(int i=1;i<=n;i++)
            scanf("%d",&target[i]);
        int ok=1;
        while(B<=n)
        {
            if(A==target[B]){A++;B++;}
            else if(top&&stack[top]==target[B]){top--;B++;}
            else if(A<=n)stack[++top]=A++;
            else {ok=0;break;}
        }
        printf("%s\n",ok?"Yes":"No");
    }
    return 0;
}

 下面还有STL栈

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

 

posted @ 2012-12-27 15:33  再见~雨泉  阅读(363)  评论(0编辑  收藏  举报