1. 程式人生 > >7-26 Windows消息隊列(25 分)(堆排序)

7-26 Windows消息隊列(25 分)(堆排序)

fix string amp malloc 有一個 queue 輸入 div ott

7-26 Windows消息隊列(25 分)

消息隊列是Windows系統的基礎。對於每個進程,系統維護一個消息隊列。如果在進程中有特定事件發生,如點擊鼠標、文字改變等,系統將把這個消息加到隊列當中。同時,如果隊列不是空的,這一進程循環地從隊列中按照優先級獲取消息。請註意優先級值低意味著優先級高。請編輯程序模擬消息隊列,將消息加到隊列中以及從隊列中獲取消息。

輸入格式:

輸入首先給出正整數N(10?5??),隨後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!


解題思路:本題主要是建立一個小頂堆,難一點的是輸出後的重建,需要模擬一下過程
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string
.h> 4 5 typedef struct Node *node; 6 struct Node 7 { 8 char mes[11]; 9 int priority; 10 }; 11 12 struct 13 { 14 node heap[100005]; 15 int num; 16 } Heap; 17 18 void Put(); 19 void Get(); 20 21 int main() 22 { 23 int n; 24 scanf("%d",&n); 25 Heap.heap[0] = (node)malloc
( sizeof(struct Node)); 26 Heap.heap[0]->priority = -1; 27 Heap.num = 0; 28 29 while( n--) 30 { 31 char op[4]; 32 getchar(); 33 scanf("%s",op); 34 switch( op[0]) 35 { 36 case P : 37 Put(); 38 break; 39 case G : 40 Get(); 41 break; 42 default : 43 break; 44 } 45 } 46 47 return 0; 48 } 49 50 51 void Put() 52 { 53 //讀入數據,建立一個小頂堆 54 int i; 55 node temp = ( node ) malloc( sizeof( struct Node)); 56 scanf("%s %d",temp->mes,&temp->priority); 57 for( i=++Heap.num; Heap.heap[i/2]->priority > temp->priority; i=i/2) 58 { 59 Heap.heap[i] = Heap.heap[i/2]; 60 } 61 Heap.heap[i] = temp; 62 } 63 64 void Get() 65 { 66 //輸出數據,重建頂堆 67 int i; 68 69 if( Heap.num<1) 70 { 71 printf("EMPTY QUEUE!\n"); 72 return ; 73 } 74 printf("%s\n",Heap.heap[1]->mes); 75 for( i=1; i*2<Heap.num; ) 76 { 77 if( i*2+1<Heap.num && Heap.heap[i*2+1]->priority<Heap.heap[i*2]->priority) 78 { 79 //如果有兩個根節點,並且右結點優先數小於左結點優先數 80 if( Heap.heap[i*2+1]->priority<Heap.heap[Heap.num]->priority) 81 { 82 Heap.heap[i] = Heap.heap[i*2+1]; 83 i=i*2+1; 84 } 85 else break; 86 } 87 else 88 { 89 if(Heap.heap[i*2]->priority < Heap.heap[Heap.num]->priority) 90 { 91 Heap.heap[i] = Heap.heap[i*2]; 92 i *= 2; 93 } 94 else break; 95 } 96 } 97 Heap.heap[i] = Heap.heap[Heap.num--]; //將最後的一個元素補在空缺 98 }

 

7-26 Windows消息隊列(25 分)(堆排序)