forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HeapPriorityQueue.c
158 lines (132 loc) · 2.28 KB
/
HeapPriorityQueue.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include<stdio.h>
#include<stdlib.h>
struct ll{
long int elem;
long int pr;
};
void swap (struct ll pq[], long int i,long int j)
{
struct ll temp = pq[i];
pq[i] = pq[j];
pq[j] =temp;
}
long size =0;
void minheapify (struct ll pq[],long int i,long int len)
{
long int l= i*2+1;
long int r = i*2 + 2;
long int smallest = i;
if((l<len)&&(pq[smallest].pr>pq[l].pr))
smallest = l;
if((r<len)&&(pq[smallest].pr>pq[r].pr))
smallest = r;
if(smallest!=i)
{
swap(pq,i, smallest);
minheapify(pq,smallest,len);
}
return;
}
void buildminheap(struct ll pq[],long int l)
{
long int i;
for(i= (l/2)-1; i>=0; i--)
minheapify(pq,i,l);
return;
}
void heapsort(struct ll pq[])
{
long int length = size;
do
{
buildminheap(pq,length);
swap(pq, 0 , length-1);
length = length-1;
}while(length>0);
}
void insert (struct ll pq[], long int data, long int num)
{
pq[size-1].elem = data;
pq[size-1].pr = num;
heapsort(pq);
}
void extract_min(struct ll pq[])
{
if(size==0)
printf("EMPTY\n");
else
{
long int n = pq[size-1].elem;
printf("%ld ", n);
printf("(%ld)\n", pq[size-1].pr);
size--;
}
return;
}
void get_min(struct ll pq[])
{
if(size==0)
printf("EMPTY\n");
else
{
long int n = pq[size-1].elem;
printf("%ld ", n);
printf("(%ld)\n", pq[size-1].pr);
}
return;
}
void decrease_priority (struct ll pq[],long int data , long int num )
{
for(long int j=0; j< size ; j++)
{
if(pq[j].elem==data)
pq[j].pr = num;
}
heapsort(pq);
}
int main()
{
struct ll *prqueue ;
prqueue = (struct ll* )malloc( sizeof(struct ll) );
char ch;
do
{
//choose the functionality
scanf("%c",&ch);
switch(ch)
{
//insert
case 'a':{
prqueue = (struct ll* ) realloc (prqueue, (++size)*sizeof(struct ll));
long int num, data;
scanf ("%ld", &data);
scanf ("%ld", &num);
insert(prqueue,data,num );
break;
}
//remove the minimum
case 'e':{
extract_min(prqueue);
break;
}
//get the minimum
case 'g':{
get_min(prqueue);
break;
}
//decrease priority of node
case 'd':{
long int num, data;
scanf ("%ld", &data);
scanf ("%ld", &num);
decrease_priority(prqueue,data, num);
break;
}
case 's': exit(0);
default : printf("error\n");
break;
}
getchar();
}while(ch!='s');
return 0;
}