From d56276cd50b030ba628091cae6f497be2545c98f Mon Sep 17 00:00:00 2001 From: Nitin Gupta <66675656+manitgupt14@users.noreply.github.com> Date: Wed, 27 Oct 2021 18:49:57 +0530 Subject: [PATCH] Stack : The Celebrity Problem Stack : The Celebrity Problem --- CelebrityProblem.cpp | 107 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 CelebrityProblem.cpp diff --git a/CelebrityProblem.cpp b/CelebrityProblem.cpp new file mode 100644 index 0000000..f848b61 --- /dev/null +++ b/CelebrityProblem.cpp @@ -0,0 +1,107 @@ +#include +using namespace std; + + + + // } Driver Code Ends +class Solution +{ + public: + priority_queue max_h; + priority_queue,greater> min_h; + int top=9999999; + //Function to insert heap. + void insertHeap(int &num) + { + if(max_h.empty() && min_h.empty() && top==9999999) + top=num; + else if(num>top) + { + if(min_h.size()>max_h.size()) + { + max_h.push(top); + min_h.push(num); + top=min_h.top(); + min_h.pop(); + } + else + { + min_h.push(num); + } + } + else if(nummax_h.size()) + { + max_h.push(num); + } + else + { + min_h.push(num); + } + } + } + + //Function to balance heaps. + void balanceHeaps() + { + + } + + //Function to return Median. + double getMedian() + { + if(max_h.size()==min_h.size()) + return top; + else if(max_h.size()>min_h.size()) + { + int k=max_h.top(); + return ((k+top)*1.0)/2; + } + else { + int k=min_h.top(); + return ((k+top)*1.0)/2; + } + return top; + } +}; + + +// { Driver Code Starts. + +int main() +{ + int n, x; + int t; + cin>>t; + while(t--) + { + Solution ob; + cin >> n; + for(int i = 1;i<= n; ++i) + { + cin >> x; + ob.insertHeap(x); + cout << floor(ob.getMedian()) << endl; + } + } + return 0; +} // } Driver Code Ends