-->

Encrypting your link and protect the link from viruses, malware, thief, etc! Made your link safe to visit.

Basic Heap Operations

This question is designed to help you get a better understanding of basic heap operations.
You will be given queries of 3  types:

1) "1 v": Add v to heap
2) "2 v":Delete v from heap
3) "3":Return minimum element

It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct elements will be in the heap.

Input Format

The first line contains the number of queries, Q.

Each of the next Qlines contains a single query of any one of the  3 above mentioned types.

Output Format
For each query of type 3, print the minimum value on a single line.

Sample Input
5  
1 4  
1 9  
3  
2 4  
3  
Sample Output
4  
9 
 
Explanation: 
After the first 2 queries, 
the heap contains {4,9}. 
Printing the minimum gives 4 as the output. 
Then, the 4th query deletes 4 from the heap, 
and the 5 query gives 9 as the output. 

Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.PriorityQueue;

public class QHeap {
    public static void main(String[] args) throws Exception{
        BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));

        int q=Integer.parseInt(bf.readLine().trim());
        PriorityQueue<Integer> pq=new PriorityQueue<>();
        for (int i = 0; i < q; i++) {
            String[] queryIp=bf.readLine().trim().split(" ");

            if(queryIp.length==1)
            {
                if(!pq.isEmpty())
                    System.out.println(pq.peek());
            }
            else            {
                if(Integer.parseInt(queryIp[0])==1)
                {
                   pq.add(Integer.parseInt(queryIp[1]));
                }
                if(Integer.parseInt(queryIp[0])==2)
                {
                    pq.remove(new Integer(queryIp[1]));
                }
            }

        }
    }
}
  

ST

Social

Recent

⬇⬇Get Your Link⬇⬇