Responsive Ads Here

Friday, 9 June 2017

Find the Running Median using heap(priority queue)

problem id:--https://www.hackerrank.com/challenges/find-the-running-median
                     http://practice.geeksforgeeks.org/problems/find-median-in-a-stream/0
code:--

#include <bits/stdc++.h>

using namespace std;
#define ll   long long
#define      pii               std::pair<int,int>
#define      vi                std::vector<int>
#define      vll               std::vector<long long>
#define      mp(a,b)           make_pair(a,b)
#define      pb(a)             push_back(a)
#define sc(x)   scanf("%d",&x)
#define scll(x)   scanf("%lld",&x)
#define sc2(x,y)   scanf("%d%d",&x,&y)
#define sc3(x,y,z)   scanf("%d%d%d",&x,&y,&z)
#define     pf(x)   printf("%d ",x)
#define     pf2(x,y)   printf("%d %d ",x,y)
#define     pf3(x,y,z)   printf("%d %d %d ",x,y,z)
#define pfnl()   putchar('\n');
#define      each(it,s)        for(auto it = s.begin(); it != s.end(); ++it)
#define      rep(i, n)         for(int i = 0; i < (n); ++i)
#define rep2(i,j,n)   for(int i = j; i < (n); ++i)
#define      fill(a)           memset(a, 0, sizeof (a))
#define      sortA(v)          sort(v.begin(), v.end())
#define      sortD(v)          sort(v.begin(), v.end(), greater<auto>())
#define all(v)   v.begin(),v.end()
#define      X                 first
#define      Y                 second


#define debug(x) cerr<<"debug->"<<#x<<"::"<<x<<endl
#define debug2(x,y) cerr<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\n"
#define debug3(x,y,z) cerr<<#x<<" :: "<<x<<"\t"<<#y<<" :: "<<y<<"\t"<<#z<<" :: "<<z<<"\n"
#define MOD 1000000007
priority_queue<double> l,r;
int  n1,n2;
double root;
void magic()
{
if(n1!=0 && n2!=0)
{
if(root<min(l.top(),-r.top()) || root>max(l.top(),-r.top()))
{
int temp=root;
root=l.top();
l.pop();
l.push(temp);
}
}
if(n1+2==n2)
{
l.push(root);
root=-r.top();
r.pop();
--n2;
++n1;
}
else if(n1==2+n2)
{
r.push(-root);
root=l.top();
l.pop();
--n1,++n2;
}
}
int main(int argc, char **argv) {
n1=0,n2=0;
int n;
double num,temp;
cin>>n;
--n;
cin>>root;
cout<<root<<"\n";
while(n--)
{
temp=0;
cin>>num;
if(root>num){l.push(num);++n1; }
else{r.push(-num);++n2;}
magic();
if(n1==n2) {cout<<root<<"\n";continue;}
temp=(n1>n2)? l.top():-r.top();
cout<<(root+temp)/2;
cout<<endl;
}
return 0;
}

No comments:

Post a Comment