Problem Description
ACboy was kidnapped!!
he miss his mother very much and is very scare now.You can't image how dark the room he was put into is, so poor :(.
As a smart ACMer, you want to get ACboy out of the monster's labyrinth.But when you arrive at the gate of the maze, the monste say :" I have heard that you are very clever, but if can't solve my problems, you will die with ACboy."
The problems of the monster is shown on the wall:
Each problem's first line is a integer N(the number of commands), and a word "FIFO" or "FILO".(you are very happy because you know "FIFO" stands for "First In First Out", and "FILO" means "First In Last Out").
and the following N lines, each line is "IN M" or "OUT", (M represent a integer).
and the answer of a problem is a passowrd of a door, so if you want to rescue ACboy, answer the problem carefully!
Input
The input contains multiple test cases.
The first line has one integer,represent the number oftest cases.
And the input of each subproblem are described above.
Output
For each command "OUT", you should output a integer depend on the word is "FIFO" or "FILO", or a word "None" if you don't have any integer.
Sample Input
4
4 FIFO
IN 1
IN 2
OUT
OUT
4 FILO
IN 1
IN 2
OUT
OUT
5 FIFO
IN 1
IN 2
OUT
OUT
OUT
5 FILO
IN 1
IN 2
OUT
IN 3
OUT
Sample Output
1
2
2
1
1
2
None
2
3
问题:这是队列与栈的应用,根据输入的FIFO和FILO来判断是用队列还是栈。当输入IN的时候表示压栈或者入队,当输入OUT的时候表示出栈或者是出队。然后根据当前的状态输出对应的元素,若没有元素了,则输出None。
1.输入T,表示测试的次数
2.第二行输入一个整数,表示每组测试需要输入的个数,接着 输入一个FIFO和FILO,表示每组存储的方式
3.当输入IN的时候,表示要压栈或入队
4.当输入OUT的时候表示要访问一个数,并将该数从栈或者队列中删除
代码如下:
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
int main()
{
int t;
scanf("%d",&t);//测试的次数
while(t--)
{
int n,temp;
stack<int> S;//定义一个栈
queue<int> Q;//定义一个队列
char a[10];
char str[3];
scanf("%d",&n);//输入每组要输入的个数
cin>>a;//输入存储方式
for(int i=0;i<n;i++)
{
cin>>str;//输入IN或者是OUT
if(a[2]=='F')//当时FIFO时,表示队列
{
if(str[0]=='I')
{
scanf("%d",&temp);
Q.push(temp);
}
else if(str[0]=='O')
{
if(Q.empty())//队列为空,输出None
printf("None\n");
else{
printf("%d\n",Q.front());//访问该队首
Q.pop();//删除队首元素
}
}
}
else//当为FILO,表示存储方式是栈
{
if(str[0]=='I')
{
scanf("%d",&temp);
S.push(temp);
}
else if(str[0]=='O')
{
if(S.empty())
printf("None\n");
else{
printf("%d\n",S.top());
S.pop();
}
}
}
}
}
return 0;
}