Windows消息队列 (25分)

消息队列是Windows系统的基础。对于每个进程,系统维护一个消息队列。如果在进程中有特定事件发生,如点击鼠标、文字改变等,系统将把这个消息加到队列当中。同时,如果队列不是空的,这一进程循环地从队列中按照优先级获取消息。请注意优先级值低意味着优先级高。请编辑程序模拟消息队列,将消息加到队列中以及从队列中获取消息。

输入格式:

输入首先给出正整数N(\le 10^5105),随后N行,每行给出一个指令——GETPUT,分别表示从队列中取出消息或将消息添加到队列中。如果指令是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!

这道题用队列 会超时  所以我们用最小堆  几个月前写的不见了  重新写一份  自己的东西丢了还是很心痛的  纯c 用c++的vector 可以短很多 

#include <stdio.h>
#include <stdlib.h>
#define maxsize 100000
struct listnode {
	char name[15];
	int flag;
};
struct hnode {
	struct listnode *data;
	int size;
};
typedef struct hnode * heap;
typedef struct listnode lnode;
heap createheap() {
	heap h = (heap)malloc(sizeof(struct hnode));
	h->data = (struct listnode*)malloc(maxsize*sizeof(struct listnode));
	h->size = 0;
	h->data[0].flag = 0;
	return h;
}
void insert(heap h, lnode x) {
	int i;
	i = ++h->size;
	for (; h->data[i / 2].flag > x.flag; i /= 2)
		h->data[i] = h->data[i / 2];
	h->data[i] = x;
	return;
}
void deletemin(heap h) {
	int parent, child;
	lnode x;
	if (h->size	== 0) {
		printf("EMPTY QUEUE!\n");
		return;
	}
	printf("%s\n", h->data[1].name);
	x = h->data[h->size--];
	for (parent = 1; parent * 2 <= h->size; parent = child) {
		child = parent * 2;
		if ((child != h->size) && (h->data[child].flag > h->data[child + 1].flag))
			child++;
		if (x.flag <= h->data[child].flag) break;
		else
			h->data[parent] = h->data[child];
	}
	h->data[parent] = x;
	return;
}
int main()
{
	int n;
	heap h=createheap();
	scanf("%d", &n);
	while (n--) {
		char str[5];
		scanf("%s", &str);
		if (str[0] == 'P') {
			lnode x;
			scanf("%s %d", &x.name, &x.flag);
			insert(h, x);
		}
		else if (str[0] == 'G')
			deletemin(h);
	}
	return 0;
}

下面是c++的  突然找到

#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;

struct listnode {
	char name[15];
	int flag;
};
bool sortflag(const listnode &m1, const listnode &m2) {
	return m1.flag < m2.flag;
}
vector<struct listnode>p;
int main()
{
	int n;
	struct listnode s;
	scanf("%d", &n);
	while (n--) {
		char str[5];
		scanf("%s", &str);
		if (str[0] == 'P') {
			char str1[15];
			int num;
			scanf("%s %d", &s.name, &s.flag);
			p.push_back(s);
			if (p.size() != 1) sort(p.begin(), p.end(), sortflag);
		}
		else if (str[0] == 'G')
			if (!p.size())
				printf("EMPTY QUEUE!\n");
			else {
				printf("%s\n", p[0].name);
				p.erase(p.begin());
			}
	}
	return 0;
}



猜你喜欢

转载自blog.csdn.net/xmzyjr123/article/details/53353414