Sort by

recency

|

413 Discussions

|

  • + 0 comments

    For all those who are having trouble with the delete operation, I hope the following link can be helpful; https://en.wikipedia.org/wiki/Binary_heap#Delete

  • + 4 comments

    my code fail 2 test erorr time limit why :(((

    #include <cstdio>
    #include <vector>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int main() {
        vector<int> arr;
        int q;
        cin >> q;
        while (q--) {
            int op;
            cin >> op;
            if(op == 1){
                int k;
                cin >> k;
                arr.push_back(k);
                push_heap(arr.begin(), arr.end(), greater<int>());
            } else if (op == 2) {
                int k;
                cin >> k;
                for (int i = 0; i < arr.size(); i++) {
                    if(arr[i] == k) {
                        swap(arr[arr.size()-1], arr[i]);
                        arr.pop_back();
                        make_heap(arr.begin(), arr.end(), greater<int>());
                        break;
                    } 
                }
            } else cout << arr[0] << endl;
        } 
        return 0;
    }```
    
  • + 5 comments

    I am confused by this problem. As best as I understand, the idea of the min-heap is that it is supposed to efficiently erase the top (minimum) element, but it is not supposed to be efficient at erasing an arbitrary element. On the other hand, I looked at other people's solutions, and they all implemented it using a set, which is not strictly speaking, correct because it would handle dublicate numbers differently. Nevertheless, the solution using a set passes all tests. Am I missing anything here?

  • + 0 comments

    in java i used a TreeSet

    public static void main(String[] args) { Scanner s = new Scanner(System.in);

        int q = s.nextInt();
        Set<Integer> heap = new TreeSet<>();
        for (int i = 0; i<q;i++) {
            int qt = s.nextInt();
            switch (qt) {
                case 1:
                    heap.add(s.nextInt());
                    break;
                case 2:
                    heap.remove(s.nextInt());
                    break;
                case 3:
                    System.out.println( heap.stream().findFirst().get() );
                    break;
            }
        }
                        s.close();
    }
    
    
    
    
        }
    
        s.close();
    }
    
  • + 1 comment

    Why this is getting TLE, where as if I create a heap class and acces custom-made delete method which is actually self.heap.remove(element) is ok??

    import heapq
    n = int(input())
    heap = []
    for _ in range(n):
      n = input().strip().split()
      if n[0] == '1':
        heapq.heappush(heap, int(n[1]))
      elif n[0] == '2':
        heap.remove(int(n[1]))
      else:
        print(heap[0])
      heapq.heapify(heap)