Windows消息队列
题目
答案
#include<iostream>
#include<queue>
using namespace std;
struct order{
char name[20];
int rank;
bool operator <(const order &a)const
{
return rank>a.rank;
}
};
priority_queue<order> q;
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
char s[10];
scanf("%s",s);
if(s[0]=='P')
{
order tmp;
scanf("%s%d",tmp.name,&tmp.rank);
q.push(tmp);
}
else if(s[0]=='G')
{
if(q.empty()) printf("EMPTY QUEUE!\n");
else
{
order tmp=q.top();
q.pop();
printf("%s\n",tmp.name);
}
}
}
}
总结
初始思路:链表(超时)
代码
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct Info* info;
struct Info{
char name[10];
int rank;
info next;
};
int main()
{
int n;
scanf("%d",&n);
info head,p,tmp;
head=(info)malloc(sizeof(struct Info));
head->next=NULL;
p=head;
while(n--)
{
char s[10];
scanf("%s",s);
if(s[0]=='P')
{
tmp=(info)malloc(sizeof(struct Info));
scanf("%s %d",tmp->name,&tmp->rank);
tmp->next=NULL;
if(!p||tmp->rank<p->rank)
{
tmp->next=head->next;
head->next=tmp;
p=head;
}
else
{
while(p->next&&tmp->rank>p->next->rank)
p=p->next;
tmp->next=p->next;
p->next=tmp;
p=head;
}
}
else if(s[0]=='G')
{
if(!head->next) cout<<"EMPTY QUEUE!"<<endl;
else
{
cout<<head->next->name<<endl;
head->next=head->next->next;
}
}
}
}
分析
这段代码逻辑上没有问题,但无法通过第三个节点
本题的时间限制为150ms,且本题的数据量最大可达105,所以需要使用一个效率更高的算法
最终思路:优先级队列(成功通过)
这个思路的代码就是答案的代码,而我也是通过其它文章学习的这个方法
如果大家对于优先级队列没有什么概念,可以到这篇文章中学习一下——c++优先队列(priority_queue)用法详解
而对于结构体中的重载运算符(operator),我推荐给大家这篇文章以供参考(大家重点看文章中的例子)——C++ operator(重载操作符)
优先级队列其实就是在普通队列的基础上增加了自动排序的功能(个人理解),其它操作与基础队列完全相同。
使用优先级队列会让我们在特定情况下事半功倍,它也是我们解题的思路之一,我在此推荐给大家。