您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之栈七:出栈序列判定

2016-10-18 20:05 232 查看

数据结构实验之栈七:出栈序列判定

Time Limit: 30MS Memory Limit: 1000KB
[align=center]Submit Statistic Discuss[/align]

Problem Description

给一个初始的入栈序列,其次序即为元素的入栈次序,栈顶元素可以随时出栈,每个元素只能入栈依次。输入一个入栈序列,后面依次输入多个序列,请判断这些序列是否为所给入栈序列合法的出栈序列。

例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个出栈序列,但4,3,5,1,2就不可能是该序列的出栈序列。假设压入栈的所有数字均不相等。

Input

 第一行输入整数n(1<=n<=10000),表示序列的长度。
第二行输入n个整数,表示栈的压入顺序。

第三行输入整数t(1<=t<=10)。

后面依次输入t行,每行n个整数,表示要判断的每一个出栈序列。

Output

 对应每个测试案例输出一行,如果由初始入栈序列可以得到该出栈序列,则输出yes,否则输出no。

Example Input

51 2 3 4 524 5 3 2 14 3 5 1 2


Example Output

yesno


Hint

 

Author

 

此题用java做TLE~~
#include<stdio.h>
#include<iostream>
using namespace std;
int Push[10010],Stack[10010],Pop[10010];
int main()
{
int n,i;
while((cin>>n)!=NULL)
{
for(i=0;i<n;i++)
cin>>Push[i];
int t;
cin>>t;
while(t--)
{
for(i=0;i<n;i++)
cin>>Pop[i];
int i=0,j=0,top=-1,flag=0;
while(j<n)
{
if(top==-1||Stack[top]<Pop[j])
{
if(top<n-1)
Stack[++top]=Push[i++];
else
{
flag=1;
break;
}
}
if(Stack[top]==Pop[j])
--top,++j;
else if(Stack[top]>Pop[j])
{
flag=1;
break;
}
}
if(flag!=1)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
}
return 0;
}


java
import java.util.Scanner;
import java.util.Stack;
public class test{
public static void main(String[] args){
Scanner cin = new Scanner(System.in);
int a[] = new int[100100];
int b[] = new int[100100];
int n = cin.nextInt();
for(int i=0;i<n;i++){
a[i] = cin.nextInt();
}
int t = cin.nextInt();
for(int i=0; i<t; i++){
for(int j=0; j<n; j++){
b[j] = cin.nextInt();
}
Stack <Integer> stack= new Stack<Integer>();
int x=0,y=0;
while(y<n){
if(a[x]==b[y]){
x++;
y++;
}
else if(x<n){//入栈
stack.push(a[x]);
x++;
}
else if(!stack.empty() && stack.peek() == b[y]){//与栈顶元素相比较
stack.pop();
y++;
}
else{
break;
}
}
if(stack.empty()){
System.out.println("yes");
}
else
{
System.out.println("no");
}
}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构