Advertisement
Guest User

Pracownik

a guest
Jan 31st, 2015
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct element {
  6.     int key;
  7.     int numer;
  8. };
  9.  
  10. element *tab;
  11. int heap_size = 0;
  12. int numer_zad = 0;
  13.  
  14. void heapify(int i) {
  15.     int l = 2 * i;
  16.     int r = 2 * i + 1;
  17.     int largest;
  18.     if ((l <= heap_size) && ((tab[l].key > tab[i].key) || (tab[l].key == tab[i].key && tab[l].numer<tab[i].numer)))
  19.         largest = l;
  20.     else
  21.         largest = i;
  22.  
  23.     if ((r <= heap_size) && ((tab[r].key > tab[largest].key) || (tab[r].key == tab[largest].key && tab[r].numer < tab[largest].numer)))
  24.         largest = r;
  25.  
  26.     if (largest != i)
  27.     {
  28.         element temp;
  29.         temp = tab[i];
  30.         tab[i] = tab[largest];
  31.         tab[largest] = temp;
  32.         heapify(largest);
  33.     }
  34. }
  35.  
  36. int heap_extract() {
  37.     int max = tab[1].numer;
  38.     tab[1] = tab[heap_size];
  39.     heap_size--;
  40.     int i = 1;
  41.     heapify(i);
  42.     return max;
  43. }
  44.  
  45. void heap_insert(int liczba){
  46.     heap_size++;
  47.     numer_zad++;
  48.     tab[heap_size].key = liczba;
  49.     tab[heap_size].numer = numer_zad;
  50.     int w = heap_size;
  51.     while (w!=1 && (tab[w].key > tab[w/2].key || (tab[w/2].key == tab[w].key && tab[w].numer < tab[w/2].numer)))
  52.     {
  53.         element temp;
  54.         temp = tab[w];
  55.         tab[w] = tab[w/2];
  56.         tab[w/2] = temp;
  57.         w = w / 2;
  58.     }
  59. }
  60.  
  61. int main(){
  62.     int ile;
  63.     cin >> ile;
  64.     tab = new element[ile + 1];
  65.     int liczba;
  66.     for (int i = 0; i < ile; i++){
  67.         cin >> liczba;
  68.         if(liczba != 0)
  69.             heap_insert(liczba);
  70.         if(liczba==0 && heap_size!=0)
  71.             cout << heap_extract() << endl;
  72.     }
  73.     delete[]tab;
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement