【模拟+数据结构】UVA 11995 I Can Guess the Data Structure!

【模拟+数据结构】UVA 11995 I Can Guess the Data Structure!

题目大意

给出一系列操作,包含操作数和操作码,判断符合这一系列操作返回值的数据结构类型(栈、队列、优先队列)

【模拟+数据结构】UVA 11995 I Can Guess the Data Structure!_第1张图片
【模拟+数据结构】UVA 11995 I Can Guess the Data Structure!_第2张图片
【模拟+数据结构】UVA 11995 I Can Guess the Data Structure!_第3张图片
【模拟+数据结构】UVA 11995 I Can Guess the Data Structure!_第4张图片

说一下思路

  • 拿这三种数据结构去模拟一下就可以了
    【注意】栈顶 stack.top()
    队首 queue.front()
    堆顶 priority_queue.top()
    堆又叫做优先队列heap == priority_queue

这里写图片描述


参考代码

#include
using namespace std;

const int _max = 1e3 + 10;

int n,op[_max],x[_max];//操作数与操作码
stack<int>stk;
queue<int>q;
priority_queue<int>pq;

bool isStack(){
  while(!stk.empty())stk.pop();
  for(int i = 0; i < n; ++ i){
    if(op[i] == 1) stk.push(x[i]);
    else{
        if(stk.empty()) return false;
        int v = stk.top();stk.pop();//栈顶top
        if(v != x[i]) return false;
    }
  }
  return true;
}

bool isQueue(){
  while(!q.empty())q.pop();
  for(int i = 0; i < n; ++ i){
    if(op[i] == 1) q.push(x[i]);
    else{
        if(q.empty()) return false;
        int v = q.front();q.pop();//队首front
        if(v != x[i]) return false;
    }
  }
  return true;
}

bool isPriority(){
  while(!pq.empty())pq.pop();
  for(int i = 0; i < n; ++ i){
    if(op[i] == 1) pq.push(x[i]);
    else{
        if(pq.empty()) return false;
        int v = pq.top();pq.pop();//堆顶top
        if(v != x[i]) return false;
    }
  }
  return true;
}

int main(){
 #ifndef ONLINE_JUDGE
 freopen("input.txt","r",stdin);
 #endif // ONLINE_JUDGE
 while(scanf("%d",&n)==1){
    for(int i = 0; i < n; ++ i)
      scanf("%d%d",op+i,x+i);
    bool ok1 = isStack(),ok2 = isQueue(),ok3 = isPriority();
    if(ok1&&!ok2&&!ok3) {puts("stack");continue;}
    if(!ok1&&ok2&&!ok3) {puts("queue");continue;}
    if(!ok1&&!ok2&&ok3) {puts("priority queue");continue;}
    if(!ok1&&!ok2&&!ok3) {puts("impossible");continue;}
    puts("not sure");
 }
 return 0;
}
  • 加粗 Ctrl + B
  • 斜体 Ctrl + I
  • 引用 Ctrl + Q
  • 插入链接 Ctrl + L
  • 插入代码 Ctrl + K
  • 插入图片 Ctrl + G
  • 提升标题 Ctrl + H
  • 有序列表 Ctrl + O
  • 无序列表 Ctrl + U
  • 横线 Ctrl + R
  • 撤销 Ctrl + Z
  • 重做 Ctrl + Y

你可能感兴趣的:(数据结构,模拟,uva)