I - A Stack or A Queue?
题目描述:
Do you know stack and queue? They’re both important data structures. A stack is a “first in last out” (FILO) data structure and a queue is a “first in first out” (FIFO) one.
Here comes the problem: given the order of some integers (it is assumed that the stack and queue are both for integers) going into the structure and coming out of it, please guess what kind of data structure it could be - stack or queue?
Notice that here we assume that none of the integers are popped out before all the integers are pushed into the structure.
Input
There are multiple test cases. The first line of input contains an integer T (T <= 100), indicating the number of test cases. Then T test cases follow.
Each test case contains 3 lines: The first line of each test case contains only one integer N indicating the number of integers (1 <= N <= 100). The second line of each test case contains N integers separated by a space, which are given in the order of going into the structure (that is, the first one is the earliest going in). The third line of each test case also contains N integers separated by a space, whick are given in the order of coming out of the structure (the first one is the earliest coming out).
Output
For each test case, output your guess in a single line. If the structure can only be a stack, output “stack”; or if the structure can only be a queue, output “queue”; otherwise if the structure can be either a stack or a queue, output “both”, or else otherwise output “neither”.
Sample Input
4
3
1 2 3
3 2 1
3
1 2 3
1 2 3
3
1 2 1
1 2 1
3
1 2 3
2 3 1
Sample Output
stack
queue
both
neither
题意:给你两个序列,判断一下,第二个序列是又第一个序列经过栈还是队列的操作得到的。(注意:第一个序列的元素必须全部进容器,才可执行出元素操作)。
分析:
本题主要考查栈和队列的基本性质。我们可以发现,对于栈而言,第一个序列和第二个序列是完全相反的。对于队列而言,第一个序列和第二个序列式完全一样的。 这样我们通过两个判断就可以的出正确的答案。
#include"stdio.h"
#include"string.h"
int main()
{
int T;
int n;
int a[101],b[101];
int i,j,k;
int mark1,mark2;
while(~scanf("%d",&T))
{
while(T--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
{
if(a[i]!=b[i])
break;
}
if(i==n)
mark1=1;
else
mark1=0;
for(i=0;i<n;i++)
if(a[i]!=b[n-1-i])
break;
if(i==n)
mark2=1;
else
mark2=0;
if(mark1==1&&mark2==1)
printf("both\n");
else
if(mark1==0&&mark2==0)
printf("neither\n");
else
if(mark1==1)
printf("queue\n");
else
if(mark2==1)
printf("stack\n");
}
}
}
还没有评论,来说两句吧...