题目大意
给一个“包”(某种数据结构)输入一些数据,然后又从中取出一部分,根据这些数据判断这个“包”是哪种数据结构,对应输入"stack", “queue”, “priority queue”, “not sure”, “impossible”。
分析
这道题是一道简单的模拟题,我们需要用STL中封装好的栈、队列和优先队列对给出的数据进行模拟,输出符合的即为要找的数据结构。这道题的坑点在于:它取出来的数的数量可能大于输入的数量,如果对一个空的栈、队列和优先队列执行pop()操作会导致Runtime Error。
对应的STL简介
1. 栈(stack)
栈是一种受限制的线性表,限定仅在表尾进行插入和删除操作,遵循“后进先出”的原则。以下是STL中关于栈的常用操作函数:
#include <stack> //header file
stack<int> s; //define a stack
s.empty(); //return value is Boolean type to determine whether the stack is empty
s.push((int)value);//Insert variables into the stack
s.top(); //returns the top element of the stack
s.pop(); //delete the top element of the stack
2. 队列(queue)
队列也是一种受限制的线性表,限定只能在表头进行删除操作,在表尾进行插入操作,遵循“先进先出”原则。
#include <queue> //header file
queue<int> q; //define a queue
q.empty();
q.push((int)value);
q.front(); //returns the header element
q.pop();
3. 优先队列(priority_queue)
在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除,遵循“最高级先出 (first in, largest out)”的原则,通常采用堆数据结构来实现。c++的STL中封装的priority_queue默认是数值比较大的数具有较高的优先级,如果我们需要改变优先级的话可以通过以下方式:
//方法一
priority_queue<int, vector<int>, greater<int> > qq;
//方法二, Define structure overload () operator
struct cmp{
bool operator() (const int a,const int b) const{
return a > b; //Numbers with small values have high priority
}
};
priority_queue<int, vector<int>, cmp> cq;
priority_queue的一些常用函数:
#include<queue>
priority_queue<int> pq;
s.empty();
s.push((int)value);
s.top(); //returns the top element of the heap
s.pop();
4.清空操作
关于以上STL容器的清空操作,很可惜他们并没有像set和map拥有clear()这样的清空函数,我们只能用类似于下面这种方法进行手动清空操作。
while(!s.empty())
s.pop();
代码如下
#include <iostream>
#include <cstdio>
#include <stack>
#include <queue>
#include <algorithm>
using namespace std;
stack<int> s;
queue<int> q;
priority_queue<int> pq;
bool sflag,qflag,pqflag;
int n,a,b;
void init() //Initialization function
{
sflag =qflag = pqflag = true;
while(!s.empty())s.pop();
while(!q.empty())q.pop();
while(!pq.empty())pq.pop();
}
int main()
{
ios::sync_with_stdio(false);
cin.tie();
while(cin>>n)
{
init();
while(n--)
{
cin>>a>>b;
if(a == 1)
{
if(sflag)s.push(b);
if(qflag)q.push(b);
if(pqflag)pq.push(b);
}
else
{
if(s.empty() || q.empty() || pq.empty())
sflag =qflag = pqflag = false;
if(sflag)
{
if(s.top() != b)
sflag = false;
s.pop();
}
if(qflag)
{
if(q.front() != b)
qflag = false;
q.pop();
}
if(pqflag)
{
if(pq.top() != b)
pqflag = false;
pq.pop();
}
}
}
if(!sflag && !qflag && !pqflag)
cout<<"impossible"<<endl;
else if((sflag && qflag) || (sflag && pqflag) || (qflag && pqflag))
cout<<"not sure"<<endl;
else if(sflag)
cout<<"stack"<<endl;
else if(qflag)
cout<<"queue"<<endl;
else
cout<<"priority queue"<<endl;
}
return 0;
}
参考资料
https://blog.csdn.net/apro1066/article/details/81814154
https://blog.csdn.net/weixin_36888577/article/details/79937886