Windows消息队列(PTA)——使用优先级队列priority_queue

题目

在这里插入图片描述
在这里插入图片描述

答案

#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(重载操作符)

优先级队列其实就是在普通队列的基础上增加了自动排序的功能(个人理解),其它操作与基础队列完全相同。

使用优先级队列会让我们在特定情况下事半功倍,它也是我们解题的思路之一,我在此推荐给大家。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值