题解 UVA11995 【I Can Guess the Data Structure!】

来自我的luogu blog

难度不大,可以用来练习STL,也可以自己手打数据结构但我太懒了

介绍一下用到的三种数据结构stackqueuepriority_queue

stack

栈的修改遵循先进后出原则,应该都知道吧

#include <stack>
stack<Typename T> s;
s.top()//返回栈顶
s.empty()//返回是否为空
s.size()//返回元素数量
s.push()//插入传入的参数到栈顶
s.pop()//弹出栈顶

queue

队列的修改遵循先进先出原则,就像你在很多地方排队一样,虽然人有可能插队

#include <queue>
queue<Typename T> q;
q.front()//返回队头
q.empty()//返回是否为空
q.size()//返回元素数量
q.push()//插入传入的参数到队尾
q.pop()//弹出队头

priority_queue

优先队列每次弹出队列当中的最高优先级元素(可以自己定义规则,例如greater<int>)。

#include <queue>
qriority_queue<Typename T> q;
q.top()//返回堆顶元素
q.empty()//返回是否为空
q.push()//插入传入的参数到堆中
q.pop()//弹出队头

本题需要让你做的就是同时进行三种数据结构的插入与弹出,判断哪一种数据结构是符合要求的。

另外还有一个坑点,每次弹出时,需要判断队列是否为空,否则可能RE。

代码:

#include<bits/stdc++.h>
using namespace std;
int n,opt,x;
stack<int> st;
queue<int> q;
priority_queue<int> pq;
int is_st,is_q,is_pq;
void clear()
{
	while(!st.empty())st.pop();
	while(!q.empty())q.pop();
	while(!pq.empty())pq.pop();
	is_st=is_q=is_pq=1;
}
void insert(int x)
{
	st.push(x);
	q.push(x);
	pq.push(x);
}
void pop(int x)
{
	if(q.empty())is_st=is_q=is_pq=0;
	else
	{
		int t=st.top();st.pop();
		if(t!=x)is_st=0;
		t=q.front();q.pop();
		if(t!=x)is_q=0;
		t=pq.top();pq.pop();
		if(t!=x)is_pq=0;
	}
}
inline int read()
{
	int x=0;char ch=getchar();
	while(!isdigit(ch))ch=getchar();
	while(isdigit(ch))x=x*10+ch-48,ch=getchar();
	return x;
}
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		clear();
		while(n--)
		{
			opt=read();x=read();
			if(opt==1)insert(x);
			else pop(x);
		}
		if(is_st&&!is_q&&!is_pq)puts("stack");
		else if(!is_st&&is_q&&!is_pq)puts("queue");
		else if(!is_st&&!is_q&&is_pq)puts("priority queue");
		else if(!(is_st||is_q||is_pq))puts("impossible");
		else puts("not sure");
		//clear();
	}
	return 0;
}
posted @ 2020-12-13 11:06  子漫  阅读(91)  评论(0编辑  收藏  举报