题目地址:http://ac.jobdu.com/problem.php?pid=1366
- 题目描述:
-
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,1是该压栈序列对应的一个弹出序列,但4,5,1,2就不可能是该压栈序列的弹出序列。
- 输入:
-
每个测试案例包括3行:
第一行为1个整数n(1<=n<=100000),表示序列的长度。
第二行包含n个整数,表示栈的压入顺序。
第三行包含n个整数,表示栈的弹出顺序。
- 样例输入:
-
- 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;
- }