寒假集训三,ACboy needs your help again! 栈,队列

9 篇文章 1 订阅
8 篇文章 0 订阅
阿忠哥的小瓜子被歹徒抢走了了 
阿忠哥特别想嗑小瓜子,希望能把瓜子抢回来。 
英勇的阿忠哥出发了,他杀进了歹徒的贼窝的时候,歹徒出了一道难题给阿忠哥,如果答不出来,那他们就要把瓜子吃完。 
问题就在墙上: 
每个问题的第一行都有一个整数 N(有N个命令),还有 "FIFO" 或 "FILO".(阿忠哥很高兴因为他知道"FIFO"代表 "First In First Out", 并且 "FILO" 代表 "First In Last Out",他觉得他的四级下次就能过了). 
接下来 N 行, 每行都是"IN M" 或者 "OUT", (M 代表一个整数). 
得到的输出答案就是存放瓜子的仓库密码锁的密码。作为一个信安专家,阿忠哥一定会破出这个密码,吃上香甜的瓜子。
Input包含多组输入 
第一行包含一个整数,代表组数 
接下来的输入如描述所述Output每得到一个 "OUT", 你必须根据 "FIFO" 或 "FILO"的原则,立刻输出一个整数, 或者如果还没有得到任何整数的话就输出 "None"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

代码如下:

#include <iostream>
#include <string>
#include <queue>
#include <stack>
using namespace std;
queue<int> q;
stack<int> s;
int n;
void Q()
{
    int num;
    char str[25];
    while(n--)
    {
        scanf("%s",str);
        if(str[0]=='I')
        {
            scanf("%d",&num);
            q.push(num);
        }else if(str[0]=='O'&&!q.empty())
        {
            printf("%d\n",q.front());
            q.pop();
        }else
        {
            printf("None\n");
        }
    }
}
void S()
{
    int num;
    char str[25];
    while(n--)
    {
        scanf("%s",str);
        if(str[0]=='I')
        {
            scanf("%d",&num);
            s.push(num);
        }else if(str[0]=='O'&&!s.empty())
        {
            printf("%d\n",s.top());
            s.pop();
        }else printf("None\n");
    }
}
int main()
{
    
    int t;
    char str[10];
    scanf("%d",&t);
    while(t--)
    {
        while(!q.empty())
        {
            q.pop();//qingkong
        }
        while(!s.empty())
        {
            s.pop();
        }
        scanf("%d %s",&n,str);
        if(str[2]=='F')
            Q();
        else S();
    }return 0;
}

这个我用字符串 ,,跟上边没有什么太大区别 但是 string 更方便一些

#include <iostream>
#include <stack>//FILO
#include <queue>//FIFO
#include <string>
using namespace std; 
queue<int> q;
stack<int> s;
int n;
void Q()
{
	int num;
	string str;
	while(n--)
	{
		cin>>str;
		if(str=="IN")
		{
			cin>>num;
			q.push(num);
		}else if(str=="OUT"&&!q.empty())
		{
			cout<<q.front()<<endl;
			q.pop();
		}else cout<<"None"<<endl;
	}
 } 
void S()
{
	int num;
	string str;
	while(n--)
	{
		cin>>str;
		if(str=="IN")
		{
			cin>>num;
			s.push(num);
		}else if(str=="OUT"&&!s.empty())
		{
			cout<<s.top()<<endl;
			s.pop();
		}else cout<<"None"<<endl;
	}
}
int main()
{
	int t;
	string st;
	cin>>t;
	while(t--)
	{
		while(!q.empty())
		q.pop();
		while(!s.empty())
		s.pop();
		cin>>n>>st;
		if(st=="FIFO")
		Q();
		else S(); 
	}
	return 0;
}


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值