Same as LintCode "Sliding Window Median", but requires more 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 namespace std;
/* Head ends here */
multiset<int> lmax, rmin;
void removeOnly1(multiset<int> &ms, int v)
{
auto pr = ms.equal_range(v);
ms.erase(pr.first);
} void remove(multiset<int> &lmax, multiset<int> &rmin, int v)
{
if(v <= *lmax.rbegin())
{
removeOnly1(lmax, v);
if(lmax.size() < rmin.size())
{
int tmp = *rmin.begin();
lmax.insert(tmp);
removeOnly1(rmin, tmp);
}
}
else if(v >= *rmin.begin())
{
removeOnly1(rmin, v);
if((lmax.size() - rmin.size()) > )
{
int tmp = *lmax.rbegin();
removeOnly1(lmax, tmp);
rmin.insert(tmp);
}
}
} void addin(multiset<int> &lmax, multiset<int> &rmin, int v)
{
if(lmax.empty())
{
lmax.insert(v);
return;
}
int lmax_v = *lmax.rbegin();
int size_l = lmax.size(), size_r = rmin.size();
if(v <= lmax_v) // to add left
{
lmax.insert(v);
if((size_l + - size_r) > )
{
int tmp = *lmax.rbegin();
rmin.insert(tmp);
removeOnly1(lmax, tmp);
}
}
else
{
rmin.insert(v);
if((size_r + )> size_l)
{
int tmp = *rmin.begin();
removeOnly1(rmin, tmp);
lmax.insert(tmp);
}
}
} void median(vector<char> s,vector<int> X) {
int n = s.size();
multiset<int> ms;
for(int i = ; 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() >)
{
long long f1 = (long long)(*lmax.rbegin());
long long f2 = (long long)(*rmin.begin());
if ((f1 + f2) % == ) {
printf("%.0lf\n",(f1*.+f2)/.);
}
else {
printf("%.1lf\n",(f1*.+f2)/.);
}
}
else
cout << "Wrong!" << endl;
}
else
{
printf("%d\n",*lmax.rbegin());
} } }
int main(void){ //Helpers for input and output int N;
cin >> N; vector<char> s;
vector<int> X;
char temp;
int tempint;
for(int i = ; i < N; i++){
cin >> temp >> tempint;
s.push_back(temp);
X.push_back(tempint);
} median(s,X);
return ;
}