本专栏持续输出数据结构题目集,欢迎订阅。
题目
消息队列是 Windows 系统的基础。对于每个进程,系统维护一个消息队列。如果在进程中有特定事件发生,如点击鼠标、文字改变等,系统将把这个消息连同表示此消息优先级高低的正整数(称为优先级值)加到队列当中。同时,如果队列不是空的,这一进程循环地从队列中按照优先级获取消息。请注意优先级值低意味着优先级高。请编辑程序模拟消息队列,将消息加到队列中以及从队列中获取消息。
输入格式:
输入第 1 行给出正整数 n(≤10^5),随后 n 行,每行给出一个指令——GET 或 PUT,分别表示从队列中取出消息或将消息添加到队列中。如果指令是 PUT,后面就有一个消息名称、以及一个正整数表示消息的优先级,此数越小表示优先级越高。消息名称是长度不超过 10 个字符且不含空格的字符串;题目保证队列中消息的优先级无重复,且输入至少有一个 GET。
输出格式:
对于每个 GET 指令,在一行中输出消息队列中优先级最高的消息的名称和参数。如果消息队列中没有消息,输出 EMPTY QUEUE!。对于 PUT 指令则没有输出。
输入样例:
9
PUT msg1 5
PUT msg2 4
GET
PUT msg3 2
PUT msg4 4
GET
GET
GET
GET
输出样例:
msg2
msg3
msg4
msg1
EMPTY QUEUE!
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 100001
typedef struct {
char name[11]; // 消息名称,最多10个字符
int priority; // 优先级值
} Message;
Message heap[MAXN]; // 最小堆数组
int size; // 当前堆的大小
// 交换两个消息
void swap(Message *a, Message *b) {
Message temp = *a;
*a = *b;
*b = temp;
}
// 插入消息到最小堆
void insert(char *name, int priority) {
int i;
Message newMsg;
strcpy(newMsg.name, name);
newMsg.priority = priority;
// 上滤操作
for (i = ++size; i > 1 && heap[i/2].priority > newMsg.priority; i /= 2) {
heap[i] = heap[i/2];
}
heap[i] = newMsg;
}
// 删除并返回优先级最高的消息
Message deleteMin() {
Message minMsg = heap[1];
Message lastMsg = heap[size--];
int parent, child;
for (parent = 1; parent * 2 <= size; parent = child) {
child = parent * 2;
if (child != size && heap[child].priority > heap[child+1].priority)
child++; // 选择较小的子节点
if (lastMsg.priority <= heap[child].priority) break;
heap[parent] = heap[child];
}
heap[parent] = lastMsg;
return minMsg;
}
int main() {
int n;
char command[5];
size = 0; // 初始化堆大小
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s", command);
if (strcmp(command, "PUT") == 0) {
char name[11];
int priority;
scanf("%s %d", name, &priority);
insert(name, priority);
} else if (strcmp(command, "GET") == 0) {
if (size == 0) {
printf("EMPTY QUEUE!\n");
} else {
Message msg = deleteMin();
printf("%s\n", msg.name);
}
}
}
return 0;
}
1128

被折叠的 条评论
为什么被折叠?



