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

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →