-
Notifications
You must be signed in to change notification settings - Fork 39
/
Heap Decrease.cpp
88 lines (87 loc) · 1.51 KB
/
Heap Decrease.cpp
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
#include <bits/stdc++.h>
using namespace std;
void swap(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int parent(int i)
{
return (i/2);
}
int left(int i)
{
return (i*2);
}
int right(int i)
{
return (i*2)+1;
}
void insert(int heap[],int *size,int val)
{
int i = (*size);
*size +=1;
heap[i] = val;
while(i!=1 && heap[parent(i)]>heap[i])
{
swap(&heap[parent(i)],&heap[i]);
i = parent(i);
}
}
int extract(int heap[],int *size)
{
int root = heap[1];
heap[1] = heap[(*size)-1];
(*size)--;
return root;
}
void heapify(int heap[],int i,int size)
{
int l = left(i);
int r = right(i);
int s = i;
if(l<size && heap[l]< heap[i])
s = l;
if(r<size && heap[r]< heap[s])
s = r;
if(s!=i)
{
swap(&heap[i],&heap[s]);
heapify(heap,s,size);
}
}
void decreaseKey(int heap[],int i,int *size)
{
heap[i] = INT_MIN;
while(i!=1 && heap[parent(i)]>heap[i])
{
swap(&heap[parent(i)],&heap[i]);
i = parent(i);
}
extract(heap,size);
heapify(heap,1,*size);
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n,k;
int size = 1;
cin>>n>>k;
int *heap =(int*) malloc(sizeof(int)*(n+1));
int a[n];
for(int i = 0;i<n;i++)
{
cin>>a[i];
insert(heap,&size,a[i]);
}
decreaseKey(heap,k,&size);
for(int i=1;i<size;i++)
cout<<heap[i]<<" ";
cout<<endl;
}
return 0;
}