UVA 11995 I Can Guess the Data Structure!(STL应用)
题意:
现在有一个数据结构s,对应两种操作: 1 x表示存放x入s. 2 x表示从s中无错的取出了x.现在要你判断s的类型是:栈,队列还是优先队列(数值大的先出),不确定或者不可能.
分析:
刘汝佳:训练指南P186例题.
由于STL已经封装了这3种数据结构,我们只要分别建立这3种数据结构模拟操作一遍即可.看看对应的stack或queue或priority_queue进行指令1或2的结果 是否 完全符合 指令2的所有结果。
最终整合3种结构的判断结果输出即可。
AC代码(新):
#include<vector>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
struct Data_Struct
{
//vc存放指令pair序列
vector<pair<int,int> > vc;
//构造函数
Data_Struct(int n)
{
for(int i=0;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
vc.push_back(make_pair(x,y));
}
}
//判断是否可能是一个栈
bool is_stack()
{
stack<int> S;
for(int i=0;i<vc.size();i++)
{
int x=vc[i].first, y=vc[i].second;
if(x==1) S.push(y);
else if(x==2)
{
if(S.empty() || S.top()!=y ) return false;
S.pop();
}
}
return true;
}
//判断是否可能是一个队列
bool is_queue()
{
queue<int> Q;
for(int i=0;i<vc.size();i++)
{
int x=vc[i].first, y=vc[i].second;
if(x==1) Q.push(y);
else if(x==2)
{
if(Q.empty() || Q.front()!=y ) return false;
Q.pop();
}
}
return true;
}
//判断是否可能是一个优先队列
bool is_priority_queue()
{
priority_queue<int> Q;
for(int i=0;i<vc.size();i++)
{
int x=vc[i].first,y=vc[i].second;
if(x==1) Q.push(y);
else
{
if(Q.empty() || Q.top()!=y )return false;
Q.pop();
}
}
return true;
}
//输出整合后的结果
void solve()
{
int S=is_stack(), Q=is_queue(), PQ=is_priority_queue();
if(S+Q+PQ==0) printf("impossible\n");
else if(S+Q+PQ==1)
{
if(S) printf("stack\n");
else if(Q) printf("queue\n");
else if(PQ) printf("priority queue\n");
}
else if(S+Q+PQ>1)
printf("not sure\n");
}
};
int main()
{
int n;
while(scanf("%d",&n)==1)
{
Data_Struct ds(n);
ds.solve();
}
return 0;
}
AC代码:
#include<iostream>
#include<cstdio>
#include<queue>
#include<stack>
using namespace std;
const int maxn=1000+100;
struct command
{
int type;
int x;
}coms[maxn];
int main()
{
int n;
while(scanf("%d",&n)==1)
{
queue<int> q;
priority_queue<int> pq;
stack<int> s;
bool ok1=true,ok2=true,ok3=true;
for(int i=0;i<n;i++)
scanf("%d%d",&coms[i].type,&coms[i].x);
for(int i=0;i<n;i++)
{
if(!ok1 && !ok2 && !ok3) break;
int t=coms[i].type,x=coms[i].x;
if(t==1)
{
if(ok1) q.push(x);
if(ok2) pq.push(x);
if(ok3) s.push(x);
}
else if(t==2)
{
if(ok1)
{
if(q.empty())ok1=false;
else
{
int y=q.front();q.pop();
if(y!=x) ok1=false;
}
}
if(ok2)
{
if(pq.empty())ok2=false;
else
{
int y=pq.top();pq.pop();
if(y!=x) ok2=false;
}
}
if(ok3)
{
if(s.empty())ok3=false;
else
{
int y=s.top();s.pop();
if(y!=x) ok3=false;
}
}
}
}
if(ok1 && !ok2 && !ok3) printf("queue\n");
else if(!ok1 && ok2 && !ok3) printf("priority queue\n");
else if(!ok1 && !ok2 && ok3) printf("stack\n");
else if(!ok1 && !ok2 && !ok3) printf("impossible\n");
else printf("not sure\n");
}
return 0;
}