Advertisement
Guest User

Untitled

a guest
May 31st, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. int h[500003];
  8. int i , n , k;
  9.  
  10. void heapup( int i )
  11. {
  12. if (i*2>1)
  13. if (h[i] < h[i/2])
  14. {
  15. swap( h[i] , h[i/2] );
  16. heapup( i/2 );
  17. }
  18. }
  19.  
  20. void heapdown( int i )
  21. {
  22.  
  23. if (i*2<=n)
  24. {
  25. if (i*2+1<=n && h[i*2]>h[i*2+1] && h[i]>h[i*2+1] )
  26. {
  27. swap(h[i*2+1],h[i]);
  28. heapdown( i*2+1 );
  29. }
  30. else if (h[i] > h[i*2] )
  31. {
  32. swap( h[i] , h[i*2] );
  33. heapdown( i*2 );
  34. }
  35. }
  36. }
  37.  
  38.  
  39. int main()
  40. {
  41. cin>>n;
  42. for (i=1; i<=n; i++)
  43. {
  44. cin>>h[i];
  45. heapup(i);
  46. }
  47. k=n;
  48. for (i=1; i<k; i++)
  49. {
  50. swap(h[1],h[n]);
  51. n--;
  52. heapdown( 1 );
  53.  
  54. }
  55. for(i=k; i>=1; i--) cout<<h[i]<<" ";
  56. return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement