Same as Lintcode "Sliding window Median", but requires + care on details-no trailing zeroes.
#include <map>#include<Set>#include<list>#include<cmath>#include<ctime>#include<deque>#include<queue>#include<stack>#include<bitset>#include<cstdio>#include<limits>#include<vector>#include<cstdlib>#include<numeric>#include<sstream>#include<iostream>#include<algorithm>using namespacestd;/*Head ends here*/Multiset<int>Lmax, rmin;voidRemoveOnly1 (multiset<int> &ms,intv) {Auto PR=Ms.equal_range (v); Ms.erase (Pr.first);}voidRemove (multiset<int> &lmax, multiset<int> &rmin,intv) { if(v <= *Lmax.rbegin ()) {removeOnly1 (Lmax, v); if(Lmax.size () <rmin.size ()) { intTMP = *Rmin.begin (); Lmax.insert (TMP); RemoveOnly1 (Rmin, TMP); } } Else if(v >= *Rmin.begin ()) {removeOnly1 (rmin, v); if((Lmax.size ()-rmin.size ()) >1) { intTMP = *Lmax.rbegin (); RemoveOnly1 (Lmax, TMP); Rmin.insert (TMP); } }}voidAddIn (multiset<int> &lmax, multiset<int> &rmin,intv) { if(Lmax.empty ()) {Lmax.insert (v); return; } intLmax_v = *Lmax.rbegin (); intsize_l = Lmax.size (), Size_r =rmin.size (); if(v <= lmax_v)//To add left{Lmax.insert (v); if((size_l +1-Size_r) >1) { intTMP = *Lmax.rbegin (); Rmin.insert (TMP); RemoveOnly1 (Lmax, TMP); } } Else{Rmin.insert (v); if((Size_r +1) >size_l) { intTMP = *Rmin.begin (); RemoveOnly1 (Rmin, TMP); Lmax.insert (TMP); } }}voidMedian (vector<Char> s,vector<int>X) {intn =s.size (); Multiset<int>MS; for(inti =0; I < n; i + +) { if(S[i] = ='R') { if(!lmax.count (x[i]) &&!Rmin.count (X[i])) {cout<<"wrong!"<<Endl; Continue; } Else{Remove (Lmax, Rmin, X[i]); } } Else{addin (Lmax, Rmin, X[i]); } if(lmax.size () = =rmin.size ()) { if(Lmax.size () >0) { Long LongF1 = (Long Long)(*Lmax.rbegin ()); Long LongF2 = (Long Long)(*Rmin.begin ()); if((F1 + F2)%2==0) {printf ("%.0lf\n", (f1*1. +f2)/2.); } Else{printf ("%.1lf\n", (f1*1. +f2)/2.); } } Elsecout<<"wrong!"<<Endl; } Else{printf ("%d\n",*Lmax.rbegin ()); } } }intMainvoid){//Helpers for input and output intN; CIN>>N; Vector<Char>s; Vector<int>X; Chartemp; intTempint; for(inti =0; i < N; i++) {cin>> Temp >>Tempint; S.push_back (temp); X.push_back (Tempint); } median (s,x); return 0;}
View Code
Hackerrank "Median Updates"