1. 程式人生 > >資料結構與演算法題目集7-26——Windows訊息佇列

資料結構與演算法題目集7-26——Windows訊息佇列

我的資料結構與演算法題目集程式碼倉:https://github.com/617076674/Data-structure-and-algorithm-topic-set

原題連結:https://pintia.cn/problem-sets/15/problems/841

題目描述:

知識點:優先佇列

思路:優先佇列

對於字串的儲存,需要用char型陣列,用string會導致測試點2超時。

C++程式碼:

#include<iostream>
#include<queue>
#include<cstring>

using namespace std;

struct message{
	char name[11];
	int priority;
	friend bool operator < (message m1, message m2){
		return m2.priority < m1.priority;
	}
};

int N;
priority_queue<message> pq;

int main(){
	scanf("%d", &N);
	char command[4], msg[11];
	int priority;
	for(int i = 0; i < N; i++){
		scanf("%s", command);
		if(command[1] == 'U'){
			scanf("%s %d", msg, &priority);
			message tempMessage;
			strcpy(tempMessage.name, msg);
			tempMessage.priority = priority;
			pq.push(tempMessage);
		}else if(command[1] == 'E'){
			if(pq.size() == 0){
				printf("EMPTY QUEUE!\n");
			}else{
				printf("%s\n", pq.top().name);
				pq.pop();
			}
		}
	}
	return 0;
} 

C++解題報告: