九度OJ 1366 栈的压入、弹出序列 【数据结构】

题目地址:http://ac.jobdu.com/problem.php?pid=1366

题目描述:

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。

输入:

每个测试案例包括3行:

第一行为1个整数n(1<=n<=100000),表示序列的长度。

第二行包含n个整数,表示栈的压入顺序。

第三行包含n个整数,表示栈的弹出顺序。

输出:

对应每个测试案例,如果第二个序列是第一个序列的弹出序列输出Yes,否则输出No。

样例输入:
51 2 3 4 54 5 3 2 151 2 3 4 54 3 5 1 2
样例输出:
YesNo
#include <stdio.h>
 
#define MAX 100000
 
int IsRight (int push[], int pop[], int n){
    int i = 0;
    int j = 0;
    int top = 0;
    int stack[MAX];
    stack[0] = push[0];
    while (i < n ){
        while (i < n && stack[top] != pop[j]){
            ++i;
            ++top;
            stack[top] = push[i];
        }
        while (stack[top] == pop[j]){
            --top;
            ++j;
        }
    }
    while (top >= 0 && j < n){
        if (stack[top] == pop[j]){
            --top;
            ++j;
        }
        else
            return 0;
    }
    return 1;
}
 
int main(void){
    int n;
    int push[MAX];
    int pop[MAX];
    int i;
 
    while (scanf ("%d", &n) != EOF){
        for (i=0; i<n; ++i)
            scanf ("%d", &push[i]);
        for (i=0; i<n; ++i)
            scanf ("%d", &pop[i]);
        if (IsRight (push, pop, n))
            printf ("Yes\n");
        else
            printf ("No\n");
    }
 
    return 0;
}


posted @ 2014-02-17 18:31  liushaobo  阅读(206)  评论(0编辑  收藏  举报