fork download
  1. #include<iostream>
  2. #include<vector>
  3.  
  4. using namespace std;
  5.  
  6. class Tree {
  7. public:
  8. vector<int>v;
  9. int root;
  10. int size;
  11. Tree() {
  12. v.push_back(-1);
  13. root = 1;
  14. size = 0;
  15. }
  16. void swap(int a, int b) {
  17. v[0] = v[a];
  18. v[a] = v[b];
  19. v[b] = v[0];
  20. }
  21. void up(int idx) {
  22. if (idx == root) {
  23. return;
  24. }
  25. else {
  26. int p = idx / 2;
  27. if (v[p] > v[idx]) {
  28. swap(p, idx);
  29. up(p);
  30. }
  31. }
  32. }
  33. void insert(int a) {
  34. v.push_back(a);
  35. size++;
  36. up(size);
  37. }
  38. void down(int idx) {
  39. int l = idx * 2;
  40. int r = idx * 2 + 1;
  41. if (r <= size) {
  42. if (v[r] > v[l]) {
  43. if (v[l] < v[idx]) {
  44. swap(l, idx);
  45. down(l);
  46. }
  47. else {
  48. return;
  49. }
  50. }
  51. else {
  52. if (v[r] < v[idx]) {
  53. swap(r, idx);
  54. down(r);
  55. }
  56. else {
  57. return;
  58. }
  59. }
  60. }
  61. else if (l <= size) {
  62. if (v[l] < v[idx]) {
  63. swap(l, idx);
  64. down(l);
  65. }
  66. else {
  67. return;
  68. }
  69. }
  70. else {
  71. return;
  72. }
  73. }
  74. void remove() {
  75. if (size == 0) {
  76. cout << 0 << '\n';
  77. return;
  78. }
  79. cout << v[root] << '\n';
  80. if (size == 1) {
  81. size--;
  82. return;
  83. }
  84. v[root] = v[size];
  85. size--;
  86. down(root);
  87. }
  88. };
  89. int main() {
  90. int a, b;
  91. Tree tr;
  92. cin >> a;
  93. while (a--) {
  94. cin >> b;
  95. if (b == 0) {
  96. tr.remove();
  97. }
  98. else {
  99. tr.insert(b);
  100. }
  101. }
  102. }
Success #stdin #stdout 0s 5276KB
stdin
4
3
0
2
0
stdout
3
3