zoj 2724 Windows Message Queue 优先队列修改优先级

本文介绍了一种使用优先队列的数据结构实现方法,并通过对比printf与cin/cout的效率,强调了在C++中适当选择I/O操作的重要性。同时,详细解析了bool operator<函数的正确用法,确保了优先队列能够正确地按照优先级进行排序。

这是一道优先队列的题目算法照着https://www.cnblogs.com/mfrbuaa/p/4468842.html敲的,在这个题目中,用printf,和scanf效率要比cin cout快三倍。
注意: bool operator <(const Message a) const, 括号中的const表示参数a对象不会被修改,最后的const表明调用函数对象不会被修改! 如果换成 bool operator <( Message a)编译会报错!
在修改优先级的时候,第二个参数比第一个小就是最小队列,反之则是最大队列。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstdlib>
#include <cstring>
using namespace std;
struct Message {
	char name[200];
	int data, priority;
	 bool operator <(const Message a) const{
		 return a.priority < priority;
	}
};
int main() {
	priority_queue<Message>q;
	char command[200];
	Message message;
	while (cin >> command) {
		if (strcmp(command, "GET") == 0) {
			if (q.empty())cout << "EMPTY QUEUE!" << endl;
			else {
				cout << q.top().name << " " << q.top().data << endl;
				q.pop();
			}
		}
		if (strcmp(command, "PUT") == 0) {
			cin >> message.name >> message.data >> message.priority;
			q.push(message);
		}
	}
	return 0;
}
这是一个使用优先队列(priority queue)的题目,可以使用C++ STL中的优先队列来实现。 以下是样例代码: ```c++ #include <iostream> #include <queue> // 包含 priority_queue 头文件 using namespace std; int main() { int n; while (cin >> n) { priority_queue<int, vector<int>, greater<int>> pq; // 定义小根堆 for (int i = 0; i < n; i++) { int x; cin >> x; pq.push(x); // 将元素加入优先队列 } int ans = 0; while (pq.size() > 1) { // 只要队列中还有两个及以上元素 int a = pq.top(); pq.pop(); int b = pq.top(); pq.pop(); ans += a + b; pq.push(a + b); // 新元素入队 } cout << ans << endl; } return 0; } ``` 在这个代码中,我们使用了C++ STL中的优先队列 `priority_queue`,它有三个模板参数: - `int`:表示队列中存储的元素类型是 `int`。 - `vector<int>`:表示队列内部使用 `vector` 作为基础容器。 - `greater<int>`:表示使用小根堆来存储元素。 在主函数中,我们首先读入元素,然后将它们加入到优先队列中。接着,我们依次取出队列中的两个最小元素,将它们相加并累加到答案中,然后将它们的和作为新元素加入到队列中。最后,当队列中只剩下一个元素时,输出答案。 需要注意的是,在使用小根堆时,我们要将模板参数 `greater<int>` 作为第三个参数传递给 `priority_queue`。如果不指定第三个参数,则默认使用大根堆。 另外,这里使用了 `while (cin >> n)` 的方式来不断读入测试用例,直到遇到输入结束符为止(比如EOF或者Ctrl+Z)。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值