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

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →