Median Updates


Problem Statement :


The median M of  numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median.


Input:
The first line is an integer, N , that indicates the number of operations. Each of the next N  lines is either a x or r x. a x indicates that x is added to the set, and r x indicates that  is removed from the set.

Output:
For each operation: If the operation is add, output the median after adding x in a single line. If the operation is remove and the number x is not in the list, output Wrong! in a single line. If the operation is remove and the number x is in the list, output the median after deleting x in a single line. (If the result is an integer DO NOT output decimal point. And if the result is a real number, DO NOT output trailing 0s.)



Note
If your median is 3.0, print only 3. And if your median is 3.50, print only 3.5. Whenever you need to print the median and the list is empty, print Wrong!


Constraints:

0 < =  N < = 10^5

For each a x or r x, x will always be a signed integer (which will fit in 32 bits).



Solution :



title-img


                            Solution in C :

In C++ :




#include <cstdio>
#include <set>
#include <cstring>
#include <string>

using namespace std;

multiset<int> s1,s2;  //0<=|s1|-|s2|<=1
char s[55];

void gao() {
int a,b;
bool f1,f2;	
	if (s1.empty()) {
		puts("Wrong!");
		return;
	}
	if (s1.size()==s2.size()) {
		a=*s1.rbegin();
		b=*s2.begin();
		f1=a%2;
		f2=b%2;
		if (f1==f2) {
			printf("%.0lf\n",(a*1.+b)/2.);
		}
		else {
			printf("%.1lf\n",(a*1.+b)/2.);
		}
	}
	else {
		printf("%d\n",*s1.rbegin());
	}
}

void gao1(int x) { //add x
	if (s1.empty()) {
		s1.insert(x);
	}
	else if (s1.size()==s2.size()) {
		s2.insert(x);
		s1.insert(*s2.begin());
		s2.erase(s2.begin());
	}
	else {
		s1.insert(x);
		s2.insert(*s1.rbegin());
		s1.erase(s1.find(*s1.rbegin()));
	}
	gao();

}

void gao2(int x) {
multiset<int>::iterator t1=s1.find(x),t2=s2.find(x);
	if ((t1==s1.end()) && (t2==s2.end())) {
		puts("Wrong!");
		return;
	}
	if (s1.size()==s2.size()) {
		if (t2!=s2.end()) {
			s2.erase(t2);
		}
		else {
			s1.erase(t1);
			s1.insert(*s2.begin());
			s2.erase(s2.begin());
		}
	}
	else if (t1!=s1.end()) {
		s1.erase(t1);
	}
	else {
		s2.erase(t2);
		s2.insert(*s1.rbegin());
		s1.erase(s1.find(*s1.rbegin()));
	}
	gao();
}

int main() {
int i,x;

	/*s1.clear();
	s2.clear();*/
	for (scanf("%d",&i);i;--i) {
		scanf("%s%d",s,&x);
		if (s[0]=='a') {
			gao1(x);
		}
		else {
			gao2(x);
		}
	}
	return 0;

}








In Java :






import java.io.*;
import java.util.*;
import java.util.ArrayList;

class Solution{
    
    private static final List<Integer> elems = new ArrayList<Integer>();
    private static int elemsSize = 0;
    
    public static void main( String args[] ) throws Exception{
		
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        int numOfOps = Integer.parseInt(br.readLine().trim());
        
        String[] command = null;
        for (int i = 0; i < numOfOps; i++){
            command = br.readLine().trim().split(" ");
            if (command[0].equals("a"))
                addElem(Integer.parseInt(command[1]));
            else
                removeElem(Integer.parseInt(command[1]));
        }
    }
    
    private static void addElem(int elem){
        int pos = Collections.binarySearch(elems, elem);
        if (pos < 0)
            pos = -pos - 1;
        
        elems.add(pos, elem);
    	elemsSize++;
    	printMedian();
    }
    
    private static void removeElem(int elem){
        int pos = Collections.binarySearch(elems, elem);
        if (pos < 0)
            System.out.println("Wrong!");
        else{
            elems.remove(pos);
            elemsSize--;
            printMedian();
        }
    }
    
    private static void printMedian(){
        if (elemsSize > 0){
            if (elemsSize % 2 == 1)
                System.out.println(elems.get(elemsSize/2));
            else{
                long median = (long)elems.get(elemsSize/2) + (long)elems.get((elemsSize/2) - 1);
                if (median % 2 == 0)
                    System.out.format("%d%n", median/2);
                else
                    System.out.format("%.1f%n", median/2.0);
            }
        }
        else{
            System.out.println("Wrong!");
            return;
    	}
    }
}






In C :





#include <stdio.h>

long long koren,a[1100000][10],i,j,k,l,m,n,b,c,d,t,tt,nn;
char ss;

void update(long long);

long long maxx(long long xx, long long yy)
{
if(xx>yy) return xx;
return yy;
}


long long maz(long long mam, long long ind)
{
long long mm;

if(ind == -1) return 0;

if(a[ind][7]==mam)
   {
   if(a[ind][6]>0) 
      {
      a[ind][6]--;
      return 1; 
      }
   
   return 0; 
   }


if(mam<a[ind][7])
  {
  mm=maz(mam,a[ind][0]);
  update(ind);
  return mm;
  }

  mm=maz(mam,a[ind][3]);
  update(ind);
  return mm;

}

long long najdi(long long nn, long long ind)
{

//printf("hladam %lld v %lld\n",nn, ind);

if(nn<=a[ind][1]) return najdi(nn, a[ind][0]);

nn-=a[ind][1];

if(nn<=a[ind][6]) return a[ind][7];

return najdi(nn-a[ind][6],a[ind][3]);
}

void update(long long ind)
{
long long ls;

  ls = a[ind][0];
  if(ls>=0)
  {
  a[ind][1] = a[ls][1]+a[ls][6]+a[ls][4];
  a[ind][2] = 1+maxx(a[ls][2],a[ls][5]);
  
//  printf("update %lld=ind %lld=lh\n",ind, a[ind][2]);
  }
  else
  {
  a[ind][1] = 0;
  a[ind][2] = 0;
  }
  
  ls = a[ind][3];
if(ls>=0)
  {
  a[ind][4] = a[ls][1]+a[ls][6]+a[ls][4];
  a[ind][5] = 1+maxx(a[ls][2],a[ls][5]);
// printf("update %lld=ind %lld=lh\n",ind, a[ind][2]);
 
  }
  else
  {
  a[ind][4] = 0;
  a[ind][5] = 0;
  }


return ;
}


void left_rotation(long long ind)
{
long long bb, cc, dd, ee,oo;

//printf("lava rot %lld=ind\n",ind);

oo = a[ind][8];

ee = a[ind][0];
bb = a[ind][3];
cc = a[bb][0];
dd = a[bb][3];

a[ind][0]=ee;
a[ind][3]=cc;
a[bb][0] = ind;
a[bb][3] = dd;

a[bb][8] = oo;
a[ind][8] = bb;
if(cc>=0) a[cc][8] = ind;


if(oo>=0)
 {
if(a[oo][0]==ind) a[oo][0] = bb;
          else   a[oo][3] = bb;
 }
 else koren=bb;         

update(ind);
update(bb);

return ;
}

void right_rotation(long long ind)
{
long long bb, oo,cc, dd, ee;

//printf("prava rot %lld=ind\n",ind);

oo = a[ind][8];

bb = a[ind][0];
ee = a[bb][0];
cc = a[bb][3];
dd = a[ind][3];

a[ind][0]=cc;
a[ind][3]=dd;
a[bb][0] = ee;
a[bb][3] = ind;

a[bb][8] = oo;
a[ind][8] =bb;
if(cc>=0) a[cc][8] = ind;

if(oo>=0)
{
if(a[oo][0]==ind) a[oo][0] = bb;
           else   a[oo][3] = bb;
}
else koren=bb;

update(ind);
update(bb);

return ;
}



void vyvazuj(long long ind)
{
long long syn;

//if(tt==3 && ind ==2) return;

//printf("vyvazujem %lld\n",ind);

//return;

if(a[ind][2]==a[ind][5]+2)
  {
  syn = a[ind][0];
  
//  printf("tu som %lld %lld\n", ind, syn);
  
  if(a[syn][2]>a[syn][5]) right_rotation(ind);
         else {
//               printf("komplik %lld=tt\n",tt);
               left_rotation(syn);
//if(tt<3)               
               right_rotation(ind);         
              }  
  return ;
  }

  syn = a[ind][3];
  
  if(a[syn][5]>a[syn][2]) left_rotation(ind);
         else {
               right_rotation(syn);
               left_rotation(ind);         
              }  
return ;
}

void vloz(long long mam,long long ind)
{
long long vy;

// printf("%lld=vy %lld %lld\n",a[ind][2]-a[ind][5],a[ind][2],a[ind][5]);
 

if(a[ind][7]==mam)
   {
   a[ind][6]++;
   return;
   }

if(mam<a[ind][7])
  {
  if(a[ind][0]>=0) vloz(mam,a[ind][0]);
       else {
             a[ind][0] = nn;
             a[nn][0] = -1;
             a[nn][1] = 0;
             a[nn][2] = 0;
             a[nn][3]=-1;
             a[nn][4]= 0;
             a[nn][5]= 0;
             a[nn][6]= 1;
             a[nn][7]= mam;
             a[nn][8]= ind;
             
             nn++;       
             }
 
  update(ind);
//  printf("..po update %lld %lld=ph\n",ind,a[ind][5]);
             
  
  vy = a[ind][2] - a[ind][5];
  if(vy>1 || vy <-1) vyvazuj(ind);
  
//  printf("%lld=vy %lld %lld\n",vy,a[ind][2],a[ind][5]);
  
  return;
  }

  if(a[ind][3]>=0) vloz(mam,a[ind][3]);
       else {
             a[ind][3]=nn;
             a[nn][0] = -1;
             a[nn][1] = 0;
             a[nn][2] = 0;
             a[nn][3]=-1;
             a[nn][4]= 0;
             a[nn][5]= 0;
             a[nn][6]= 1;
             a[nn][7]= mam;
             a[nn][8]= ind;
             nn++;       
             }
 
 update(ind);            
  
//  printf("po update %lld %lld=ph\n",ind,a[ind][5]);
  
  vy = a[ind][2] - a[ind][5];

//  printf("%lld=vy %lld %lld\n",vy,a[ind][2],a[ind][5]);

  if(vy>1 || vy <-1) vyvazuj(ind);


return;
}



int main()
{

n=0;
nn=1;
a[0][0]=-1;
a[0][1]=0;
a[0][2]= 0;
a[0][3]=-1;
a[0][4]= 0;
a[0][5]= 0;
a[0][6]= 0;
a[0][7]= -1;
a[0][8]=-1;
koren=0;

scanf("%lld\n",&t);
for(tt=0;tt<t;tt++)
{
scanf("%c %lld\n",&ss,&k);

//printf("zac %c %lld %lld=t\n",ss,k,t);

m=1;

if(ss=='a') 
   {
   vloz(k,koren);  
   n++;
   }

if(ss=='r')
  {
  if(m=maz(k,koren)) n--;
  }

if(m==0 || n==0) printf("Wrong!\n");
  else 
    {
    if(n&1) printf("%lld\n",najdi(n/2+1,koren));
       else 
         {
         i = najdi(n/2,koren)+ najdi(n/2+1,koren);
          
          if(i<0) {printf("-");i = -i;}         
                    
          if((i&1)==0) printf("%lld\n",i/2);
               else  printf("%lld.5\n",i/2);
         }
    }

/*
for(i=0;i<nn;i++)
  printf("%lld=ind, %lld=ls %lld=ps %lld=h %lld=hl %lld=hp %lld=otec\n",i,a[i][0],a[i][3],a[i][7],a[i][2],a[i][5],a[i][8]);
 printf("----- %lld %lld\n",tt,t); 
*/
//if(tt==4) break;

}

return 0;
}











In Python3 :






'''
Created on Apr 5, 2013

@author: zeroshiiro
'''

from bisect import bisect_left

class MedianFinder:
    def __init__(self):
        self.items = []
        
    def addItem(self, num):
        position = bisect_left(self.items, num)
        self.items.insert(position, num)
        return self.median()
        
        
    def remItem(self, num):
        position = bisect_left(self.items, num)
        if(position >= len(self.items) or self.items[position] != num):
            return "Wrong!"
        else:
            del(self.items[position])
            return self.median()
    
    def median(self):
        l = len(self.items)
        if(l == 0):
            return "Wrong!"
        elif(l & 1):
            return self.items[int(l/2)]
        else:
            ans = self.items[int(l/2)] + self.items[int(l/2) - 1]
            if(ans == 0):
                return 0
            elif(ans & 1):
                return ans/2
            else:
                return int(ans/2)
        
N = int(input())
arr = MedianFinder()
for i in range(N):
    Q = input().split(" ")
    num = int(Q[1])
    if(Q[0] == "a"):
        print(arr.addItem(num))
    elif(Q[0] == "r"):
        print(arr.remItem(num))
                        








View More Similar Problems

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →