I wrote a Heap, but the judge system reports "time limit exceeded" in some tests. I use a sift_down
to build, so I don't know why.
Maybe I can improve the build? Or do I have a bad sift_down
?
Input:
n
commandsCommands:
0 xxx, where xxx is a number to add to heap
1 - extract maximum from heap
#include <iostream>
using namespace std;
int j = 0;
int sift_down(long long int *a, int i, int n){
int l = 2 * i;
int r = 2 * i + 1;
int largest = i;
if (l <= n && a[l] > a[i])
largest = l;
else
largest = i;
if (r <= n && a[r] > a[largest])
largest = r;
if (largest != i){
long long int x = a[i];
a[i] = a[largest];
a[largest] = x;
sift_down(a, largest, n);
}
return largest;
}
void sift_up(long long int *a, int i){
long long x = a[i];
while (i > 1 && a[i / 2] < x){
a[i] = a[i / 2];
i /= 2;
}
a[i] = x;
// cout << i << endl;
}
void Extract_Max(long long int *a, int *n){
long long int z = a[1];
a[1] = a[*n];
(*n)--;
sift_down(a, j = 1, *n);
cout << z << endl;
}
int main(){
int n = 0;
int k = 0;
int l = 0; //len
int command = 0;
cin >> k;
long long int *a = new long long int[k + 1]; // n <= k
for (int i = 0; i < k; i++){
cin >> command;
if (command == 0){
cin >> a[++n];
}
else {
for(int i = n - 1; i >= 1; i--)
sift_down(a, i, n);
Extract_Max(a, &n);
}
}
delete []a;
return 0;
}
sift_up
after you have inserted an item at the end of the heap in your main?sift_up
is never used. \$\endgroup\$sift_down
n-1 times beforeExtract_Max
. The onesift_down
inExtract_Max
should be sufficient to reorder the heap after deleting the root. \$\endgroup\$j
is not necessary. It is set once inExtract_Max
but never read. You can replace inExtract_Max
sift_down(a, j = 1, *n);
withsift_down(a, 1, *n);
\$\endgroup\$