思路:分别定义栈,队列,优先队列(数值大的优先级越高)。每次放入的时候,就往分别向三个数据结构中加入这个数;每次取出的时候就检查这个数是否与三个数据结构的第一个数(栈顶,队首),不相等就排除这个数据结构,可以用三个标志变量来标志可能的数据结构。
注意:可能会出现数据结构为空的情况,要先判断非空才能取元素。
AC代码
#include <stdio.h>
#include <stack>
#include <queue>
using namespace std;
//分别定义栈,队列,优先队列,然后模拟
stack<int> sta;
queue<int> que;
priority_queue<int> p_que;
void init() {
while(!sta.empty()) sta.pop();
while(!que.empty()) que.pop();
while(!p_que.empty()) p_que.pop();
}
int main() {
int n;
while(scanf("%d", &n) == 1) {
init();
int tag1 = 1, tag2 = 1, tag3 = 1;
for(int i = 0; i < n; ++i) {
int tag, num;
scanf("%d %d", &tag, &num);
if (tag == 1) {
sta.push(num);
que.push(num);
p_que.push(num);
} else if(tag == 2) {
if (sta.empty() || sta.top() != num) {
tag1 = 0;
} else sta.pop();
if (que.empty() || que.front() != num) {
tag2 = 0;
} else que.pop();
if (p_que.empty() || p_que.top() != num) {
tag3 = 0;
} else p_que.pop();
}
}
int res = tag1 + tag2 + tag3;
if (res == 0) {
printf("impossible\n");
} else if(res >= 2) {
printf("not sure\n");
} else {
if (tag1) {
printf("stack\n");
} else if (tag2) {
printf("queue\n");
} else printf("priority queue\n");
}
}
return 0;
}
如有不当之处欢迎指出!