自定义二叉堆模板.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. class tph_inc {
  2. private:
  3. template<typename _T>
  4. static void swap(_T& a, _T& b) {
  5. _T t = a;
  6. a = b;
  7. b = t;
  8. }
  9. template<typename _T, typename _U>
  10. static void up(int at, int& siz, _T* heap, bool(*comp)(_U, _U)) {
  11. while (at > 1 && !((*comp)(heap[at >> 1], heap[at]))) {
  12. swap(heap[at >> 1], heap[at]);
  13. at >>= 1;
  14. }
  15. }
  16. template<typename _T, typename _U>
  17. static void down(int at, int& siz, _T* heap, bool(*comp)(_U, _U)) {
  18. while ((at << 1) <= siz) {
  19. int mson = at << 1;
  20. if (mson + 1 <= siz && (*comp)(heap[mson + 1], heap[mson]))
  21. mson++;
  22. if ((*comp)(heap[at], heap[mson]))
  23. break;
  24. swap(heap[at], heap[mson]);
  25. at = mson;
  26. }
  27. }
  28. public:
  29. template<typename _T, typename _U>
  30. static void ins(_T x, int& siz, _T* heap, bool(*comp)(_U, _U)) {
  31. heap[++siz] = x;
  32. up(siz, siz, heap, comp);
  33. }
  34. template<typename _T, typename _U>
  35. static void del(int at, int& siz, _T* heap, bool(*comp)(_U, _U)) {
  36. swap(heap[at], heap[siz]);
  37. heap[siz--] = 0;
  38. if ((!((*comp)(heap[at >> 1], heap[at]))))
  39. up(at, siz, heap, comp);
  40. else
  41. down(at, siz, heap, comp);
  42. }
  43. };