Problem:


Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

1 \leq Q \leq 2 \times 10^5

-10^9 \leq a, b \leq 10^9

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000



Sample input:
4
1 4 2
2
1 1 -8
2


Sample output:
4 2
1 -3

Submission status: Accepted

Solution code:
class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0]*(n+1)

    def __iter__(self):
        psum = 0
        for i in range(self.size):
            csum = self.sum(i+1)
            yield csum - psum
            psum = csum
        raise StopIteration()

    def __str__(self):  # O(nlogn)
        return str(list(self))

    def sum(self, i):
        # [0, i) の要素の総和を返す
        if not (0 <= i <= self.size): raise ValueError("error!")
        s = 0
        while i>0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        if not (0 <= i < self.size): raise ValueError("error!")
        i += 1
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

    def __getitem__(self, key):
        if not (0 <= key < self.size): raise IndexError("error!")
        return self.sum(key+1) - self.sum(key)

    def __setitem__(self, key, value):
        # 足し算と引き算にはaddを使うべき
        if not (0 <= key < self.size): raise IndexError("error!")
        self.add(key, value - self[key])

N = int(input())
b_sum = 0
Q1 = []
Q = []
vars = []
for _ in range(N):
    Qu = list(map(int, input().split()))
    Q.append(Qu)
    if Qu[0]==1:
        _, a, b = Qu
        vars.append(a)
        #b_sum += b
    else:
        pass
vars = list(set(vars))
vars.sort()
d = dict((v, i) for i, v in enumerate(vars))
lend = len(d)
bit = Bit(lend)
bit2 = Bit(lend)
n = 0
for q in Q:
    if q[0]==1:
        _, a, b = q
        bit.add(d[a], a)
        bit2.add(d[a], 1)
        b_sum += b
        n += 1
    else:
        l, r = 0, len(vars)
        con = (n - 1) >> 1
        while l+1 < r:
            c = (l+r)>>1
            cnt = bit2.sum(c)
            if cnt <= con:
                l = c
            else:
                r = c
        idx = l
        v = vars[idx]
        m = bit2.sum(idx)
        s = bit.sum(idx)
        m_ = bit2.sum(lend) - m
        s_ = bit.sum(lend) - s
        ans = b_sum + m*v-s + s_-m_*v
        print(v, ans)

Submission status: Accepted

Solution code:
import heapq

def main(): 
    smaller = []
    larger = []

    smallsum = 0
    largesum = 0

    const = 0

    q = int(input())
    for _ in range(q):
        inp = input()
        if inp[0] == '1':
            _,a,b = [int(x) for x in inp.split()]
            const += b

            if not smaller:
                smaller.append(-a)
                smallsum += a

            elif a <= -smaller[0]:
                heapq.heappush(smaller, -a)
                smallsum += a

            else:
                heapq.heappush(larger, a)
                largesum += a

            while len(smaller)>len(larger)+1:
                a = -heapq.heappop(smaller)
                smallsum -= a
                heapq.heappush(larger, a)
                largesum += a
            while len(larger)>len(smaller):
                a = heapq.heappop(larger)
                largesum -= a
                heapq.heappush(smaller,-a)
                smallsum += a

        else:
            x = (-smaller[0]) if smaller else (-10**9)
            print x, const + len(smaller)*x - smallsum + largesum - len(larger)*x


######## Python 2 and 3 footer by Pajenegod and c1729

# Note because cf runs old PyPy3 version which doesn't have the sped up
# unicode strings, PyPy3 strings will many times be slower than pypy2.
# There is a way to get around this by using binary strings in PyPy3
# but its syntax is different which makes it kind of a mess to use.

# So on cf, use PyPy2 for best string performance.

py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.getvalue())
            self.truncate(0), self.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            self.write = lambda s:self.buffer.write(s.encode('ascii'))
            self.read = lambda:self.buffer.read().decode('ascii')
            self.readline = lambda:self.buffer.readline().decode('ascii')


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = sys.stdin.readline

# Cout implemented in Python
import sys
class ostream:
    def __lshift__(self,a):
        sys.stdout.write(str(a))
        return self
cout = ostream()
endl = '\n'

# Read all remaining integers in stdin, type is given by optional argument, this is fast
def readnumbers(zero = 0):
    conv = ord if py2 else lambda x:x
    A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read()
    try:
        while True:
            if s[i] >= b'0' [0]:
                numb = 10 * numb + conv(s[i]) - 48
            elif s[i] == b'-' [0]: sign = -1
            elif s[i] != b'\r' [0]:
                A.append(sign*numb)
                numb = zero; sign = 1
            i += 1
    except:pass
    if s and s[-1] >= b'0' [0]:
        A.append(sign*numb)
    return A

if __name__== "__main__":
  main()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
q0=int(input())
from heapq import *

low=[]
high=[]
ans=0
num=0
for _ in range(q0):
    q = [int(i) for i in input().split()]
    if q[0] == 1:
        ans+=q[2]
        num+=1
        a=q[1]
        if num==1:
            heappush(low,-a)
            df = 0
        elif num%2==1:
            centold = -low[0]
            centold2 = high[0]
            if -low[0] >= a:
                heappush(low,-a)
            else:
                c=heappushpop(high,a)
                heappush(low,-c)
            centnew = -low[0]
            if centnew < centold:
                df = 2*(centold-centnew)
            elif centnew <= centold2:
                df = 0
            else:
                df = 2*(centnew - centold2)
        else:
            centold = -low[0]
            if -low[0] > a:
                c=heappushpop(low,-a)
                heappush(high,-c)
            else:
                heappush(high,a)
            centnew = -low[0]
            if centnew < centold:
                df = (centold-centnew)
            else:
                df = (centnew - centold)
        df += abs(-low[0]-a)
#        print(low,high)        
        ans += df
            
        
        
        

    if q[0] == 2:
        print(-low[0],ans)

Submission status: Accepted

Solution code:
class BITree:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def calc(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

Q=int(input())
query=[list(map(int,input().split())) for i in range(Q)]
tmp=[]
for i in range(Q):
    seq=query[i]
    if len(seq)==1:
        continue
    else:
        tmp.append((seq[1],i))
tmp.sort()
X=[(-1,-1) for i in range(Q)]
for i,sq in enumerate(tmp):
    X[sq[1]]=(i+1,sq[0])
N=len(tmp)
Idx=BITree(N)
Clc=BITree(N)
Btm=0
nowindex=0
for i in range(Q):
    if X[i]==(-1,-1):
        left=1
        right=N
        mid=(left+right)//2
        while(left<=right):
            mid=(left+right)//2
            if Idx.calc(mid)<(nowindex+1)//2:
                left=mid+1
            else:
                right=mid-1
        k=left
        x=(Clc.calc(k)-Clc.calc(k-1))
        ans=Clc.calc(N)-2*Clc.calc(k)-x*(Idx.calc(N)-2*Idx.calc(k))+Btm
        print(x,ans)
    else:
        Idx.add(X[i][0],1)
        Clc.add(X[i][0],X[i][1])
        Btm+=query[i][2]
        nowindex+=1

Submission status: Accepted

Solution code:
Q = int(input())

from heapq import *

lows = []
highs = []

a = []
b = 0
r = 0

for i in range(Q):
    vs = [int(_) for _ in input().split()]
    if vs[0] == 1:
        b += vs[2]
        if not lows:
            x = vs[1]
            heappush(lows, -x)
        else:
            r += abs(vs[1] + lows[0])
            if vs[1] <= -lows[0]:
                heappush(lows, -vs[1])
            else:
                heappush(highs, vs[1])

        if len(lows) < len(highs):
            x = heappop(highs)
            y = -lows[0]
            r += y - x
            heappush(lows, -x)
        elif len(lows) > len(highs) + 1:
            x = -heappop(lows)
            y = highs[0] if len(highs) else 0
            heappush(highs, x)
            # r += x - y

        # print("center", -lows[0], r, lows, highs)

    else:
        print(-lows[0], r + b)

Submission status: Accepted

Solution code:
import heapq
spq = []
bpq = []
#que_small=queue.PriorityQueue()
small_sum=0
que_s_size=0
que_b_size=0
#que_big=queue.PriorityQueue()
big_sum=0

Q=int(input())
ans = []
b_sum=0
for i in range(Q):
    q=input().split()    
    if len(q)>1:
        a=int(q[1])
        if que_s_size==0:
            heapq.heappush(spq,-a)
            small_sum+=a
            que_s_size+=1
        elif que_s_size>que_b_size:
            c=-heapq.heappop(spq)
            small_sum-=c
            if c>a:
                #que_big.put(c)
                heapq.heappush(bpq,c)
                big_sum+=c
                heapq.heappush(spq,-a)
                #que_small.put(-a)
                small_sum+=a
            else:
                #que_big.put(a)
                heapq.heappush(bpq,a)
                big_sum+=a
                #que_small.put(-c)
                heapq.heappush(spq,-c)
                small_sum+=c
            que_b_size+=1
        else:
            c=-heapq.heappop(spq)
            small_sum-=c
            d=heapq.heappop(bpq)
            big_sum-=d
            if a>d:
                #que_big.put(a)
                heapq.heappush(bpq,a)
                big_sum+=a
                #que_small.put(-c)
                #que_small.put(-d)
                heapq.heappush(spq,-c)
                heapq.heappush(spq,-d)
                small_sum+=c+d
            else:
                #que_big.put(d)
                heapq.heappush(bpq,d)
                big_sum+=d
                #que_small.put(-a)
                #que_small.put(-c)               
                heapq.heappush(spq,-a)
                heapq.heappush(spq,-c)
                small_sum+=a+c
            que_s_size+=1

        b_sum+=int(q[2])
    else:
        if que_s_size>que_b_size:
            c=-heapq.heappop(spq)
            S = b_sum+big_sum-small_sum+c
            ans.append(str(c)+" "+str(S))
            #que_small.put(-c)
            heapq.heappush(spq,-c)
        else:
            c=-heapq.heappop(spq)
            S = b_sum+big_sum-small_sum
            ans.append(str(c)+" "+str(S))
            #que_small.put(-c)
            heapq.heappush(spq,-c)
            

for a in ans:
    print(a)

Submission status: Accepted

Solution code:
import heapq

q = int(input())

# 中央値との大小で集団を２つに分けて管理したいぞ
_,a,b = map(int, input().split())
a_large = []
a_small = [-a]
cnt_large = 0
cnt_small = 1
mean = 0
cons = b
total = 0

for i in range(q-1):
    query = input()
    if query[0] == '1':
        _,a,b = map(int, query.split())
        cons = cons + b
        if a < -a_small[0]:
            # 最大ヒープ
            heapq.heappush(a_small, -a)
            total += -(a - -a_small[0])
            cnt_small += 1
            if cnt_small > cnt_large + 1:
                old_mean = -a_small[0]
                heapq.heappush(a_large, -heapq.heappop(a_small))
                cnt_small -= 1
                cnt_large += 1
                new_mean = -a_small[0]
                total += (new_mean- old_mean) * (cnt_large - cnt_small)
        else:
            # 最小ヒープ
            heapq.heappush(a_large, a)
            total += (a - -a_small[0])
            cnt_large += 1
            if cnt_large > cnt_small:
                old_mean = -a_small[0]
                heapq.heappush(a_small, -heapq.heappop(a_large))
                cnt_small += 1
                cnt_large -= 1
                new_mean = -a_small[0]
                total += (new_mean-old_mean) * (cnt_large - cnt_small)
    else:
        x = -a_small[0]
        print(x, total+cons)

Submission status: Accepted

Solution code:
from heapq import *

def main():
    from sys import stdin, stdout

    def read():
        return stdin.readline().rstrip('\n')

    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)

    def read_int():
        return int(read())

    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]

    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)

    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)

    lower_heap = []
    higher_heap = []
    median = constant = sum_lower = sum_higher = 0
    for _ in range(read_int()):
        ar = read_int_array()
        if len(ar) == 3:
            constant += ar[2]
            x = ar[1]
            if not lower_heap:
                lower_heap.append(-x)
                sum_lower += x
                median = x
            elif not higher_heap:
                heappush(lower_heap, -x)
                sum_lower += x

                x = -heappop(lower_heap)
                sum_lower -= x
                heappush(higher_heap, x)
                sum_higher += x
                median = -lower_heap[0]
            elif x <= -lower_heap[0]:
                heappush(lower_heap, -x)
                sum_lower += x

                if len(lower_heap) - len(higher_heap) > 1:
                    x = -heappop(lower_heap)
                    sum_lower -= x
                    heappush(higher_heap, x)
                    sum_higher += x
                median = -lower_heap[0]
            else:
                heappush(higher_heap, x)
                sum_higher += x
                if len(higher_heap) > len(lower_heap):
                    x = heappop(higher_heap)
                    sum_higher -= x
                    heappush(lower_heap, -x)
                    sum_lower += x
                median = -lower_heap[0]
        else:
            write(median, constant + abs(sum_lower - median * len(lower_heap)) + abs(sum_higher - median * len(higher_heap)))
main()

Submission status: Accepted

Solution code:
# Binary Indexed Tree (Fenwick Tree)
class BIT():

    def __init__(self, n):
        '''
        n = 要素数
        添字は i = 0 ~ n-1 となる
        '''
        self.n = n
        self.bit = [0] * (n + 1)

    def add(self, i, x):
        '''i番目の要素にxを加算する'''
        i = i + 1
        while i <= self.n:
            self.bit[i] += x
            i += i & -i

    def _sum(self, i):
        s = 0
        while i > 0:
            s += self.bit[i]
            i -= i & -i
        return s

    def get(self, i, j):
        '''[i, j)の和を求める'''
        return self._sum(j) - self._sum(i)

      
def solve():
    ok = len_memo
    ng = 0
    while abs(ok - ng) > 1:
        mid = (ok + ng) // 2
        if 2 * bit1.get(mid, len_memo) <= cnt :
            ok = mid
        else:
            ng = mid
    return memo_inv[ng]
    

def compress(list1):
    list2 = sorted(set(list1))
    memo = {value : index for index, value in enumerate(list2)}
    #for i in range(len(list1)):
    #    list1[i] = memo[list1[i]]
    return memo, len(list2)

q = int(input())
info = [list(map(int, input().split())) for i in range(q)]

#座圧する
li1 = []
for i in range(q):
    if info[i][0] == 1:
        li1.append(info[i][1])

memo, len_memo = compress(li1)
memo_inv = dict([(v,k) for k,v in memo.items()])
#print(memo)
#print(memo_inv)

#値を管理するBIT
bit = BIT(len_memo)
#要素数を管理するBITに
bit1 = BIT(len_memo)

x = []
b = 0
cnt = 0
for i in range(q):
    if info[i][0] == 1:
        bit.add(memo[info[i][1]], info[i][1])
        bit1.add(memo[info[i][1]], 1)
        b += info[i][2]
        cnt += 1
    if info[i][0] == 2:
        median_x = solve()
        sum1 = bit.get(0, memo[median_x])
        num1 = bit1.get(0, memo[median_x])
        sum2 = bit.get(memo[median_x], len_memo)
        num2 = bit1.get(memo[median_x], len_memo)
        #print(median_x, sum1,num1, sum2, num2)
        print(median_x, abs(num1*median_x - sum1) + abs(num2*median_x - sum2) + b)

Submission status: Accepted

Solution code:
import sys
import heapq

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

q = ni()

lh = []
hh = []
ln = 0
hn = 0
ls = 0
hs = 0
off = 0
for z in range(q):
    line = na()
    if line[0] == 1:
        _, a, b = line
        off += b

        if len(lh) > 0:
            mid = -lh[0]
            if a <= mid:
                heapq.heappush(lh, -a)
                ls += a
                ln += 1
            else:
                heapq.heappush(hh, a)
                hs += a
                hn += 1
        else:
            heapq.heappush(lh, -a)
            ls += a
            ln += 1

        while ln < hn:
            mx = heapq.heappop(hh)
            hs -= mx
            hn -= 1
            ls += mx
            ln += 1
            heapq.heappush(lh, -mx)

        while ln > hn + (ln+hn)%2:
            mx = -heapq.heappop(lh)
            ls -= mx
            ln -= 1
            heapq.heappush(hh, mx)
            hs += mx
            hn += 1
    else:
        lls = -lh[0]*ln - ls
        hhs = hs - (-lh[0]*hn)
        print(-lh[0], lls+hhs+off)

Submission status: Accepted

Solution code:
from collections import defaultdict as ddic, deque, Counter
from itertools import permutations, combinations, product
import bisect, heapq
import Queue as queue 
rr = raw_input
rri = lambda: int(raw_input())
rrm = lambda: map(int, raw_input().split())

lower = []  # stored as negative
upper = []
sums = [0, 0]
def add(x):
    if len(lower) <= len(upper):
        heapq.heappush(lower, -x)
        sums[0] += x
    else:
        heapq.heappush(upper, x)
        sums[1] += x
    while lower and upper and -lower[0] > upper[0]:
        left = -heapq.heappop(lower)
        right = heapq.heappop(upper)
        sums[0] -= left
        sums[1] -= right
        heapq.heappush(lower, -right)
        heapq.heappush(upper, left)
        sums[0] += right
        sums[1] += left
    
    
B = [0]
def update(a, b):
    # f(x) += |x-a| + b
    B[0] += b
    add(a)
    
def report():
    # x that minimizes f(x)
    
    median = -lower[0]
    val = B[0]
    val += len(lower) * median - sums[0]
    val += sums[1] - len(upper) * median
    return median, val
    

Q = rri()
for _ in xrange(Q):
    query = rrm()
    if query[0] == 1:
        update(query[1], query[2])
    else:
        m,v = report()
        print m, v

Submission status: Runtime Error

Solution code:
import sys
import io, os
#input = sys.stdin.buffer.readline
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

Q = int(input())
cnt = 0
m = []
M = []
import heapq
heapq.heapify(m)
heapq.heapify(M)
sum_m = 0
sum_M = 0
B = 0
cnt = 0
for i in range(Q):
    #print(m, M)
    q = str(input())
    if q != '2':
        _, a, b = map(int, q.split())
        B += b
        cnt += 1
        if len(m) != 0 and len(M) != 0:
            x1 = heapq.heappop(m)*(-1)
            x2 = heapq.heappop(M)
            sum_m -= x1
            sum_M -= x2
            if a <= x2:
                heapq.heappush(m, a*(-1))
                heapq.heappush(m, x1*(-1))
                sum_m += a+x1
                heapq.heappush(M, x2)
                sum_M += x2
            else:
                heapq.heappush(M, a)
                sum_M += a
                heapq.heappush(m, x1*(-1))
                heapq.heappush(M, x2*(-1))
                sum_m += x1+x2
        elif len(m) != 0 and len(M) == 0:
            x1 = heapq.heappop(m)*(-1)
            sum_m -= x1
            if a <= x1:
                heapq.heappush(m, a*(-1))
                sum_m += a
                heapq.heappush(M, x1)
                sum_M += x1
            else:
                heapq.heappush(M, a)
                sum_M += a
                heapq.heappush(m, x1*(-1))
                sum_m += x1
        else:
            heapq.heappush(m, a*(-1))
            sum_m += a
    else:
        if cnt == 0:
            print(0, 0)
        else:
            m_ = len(m)
            M_ = len(M)
            x = heapq.heappop(m)*(-1)
            min_ = sum_M - sum_m + m_*x - M_*x + B
            #print(sum_M, sum_m, B)
            print(x, min_)
            heapq.heappush(m, x*(-1))

Submission status: Runtime Error

Solution code:
import sys
import io, os
input = sys.stdin.buffer.readline
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

q = int(input())

import heapq
h1 = []
h2 = []
heapq.heapify(h1)
heapq.heapify(h2)

B = 0
S1 = 0
S2 = 0

for i in range(q):
    query = list(map(int, input().split()))
    if query[0] == 1:
        a, b = query[1], query[2]
        B += b
        if len(h1) == 0:
            heapq.heappush(h1, a*(-1))
            S1 += a
        elif len(h2) == 0:
            x = heapq.heappop(h1)*(-1)
            S1 -= x
            if x <= a:
                heapq.heappush(h1, x*(-1))
                heapq.heappush(h2, a)
                S1 += x
                S2 += a
            else:
                heapq.heappush(h1, a*(-1))
                heapq.heappush(h2, x)
                S1 += a
                S2 += x
        else:
            x = heapq.heappop(h1)*(-1)
            y = heapq.heappop(h2)
            S1 -= x
            S2 -= y
            if a <= y:
                heapq.heappush(h1, x*(-1))
                heapq.heappush(h1, a*(-1))
                heapq.heappush(h2, y)
                S1 += x+a
                S2 += y
            else:
                heapq.heappush(h1, x*(-1))
                heapq.heappush(h1, y*(-1))
                heapq.haeppush(h2, a)
                S1 += x+y
                S2 += a
    else:
        t = h1[0]*(-1)
        ans = t*len(h1)-S1+S2-t*len(h2)+B
        print(t, ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline


class BIT:
    def __init__(self, n):
        self.n = n
        self.bit = [0]*(n+1)
        self.value = [0]*(n+1)
    
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.bit[i]
            i -= i & -i
        return s
    
    def add(self, i, x):
        # assert i > 0
        self.value[i] += x
        while i <= self.n:
            self.bit[i] += x
            i += i & -i
    
    def subtract(self, i, x):
        self.add(i, -x)
    
    def init(self, n, lis):
        self.n = n
        self.bit = [0]*(n+1)
        self.value = lis
        for i in range(n):
            self.add(i, lis[i])
            
    def get_value(self, i):
        return self.value[i]
    
    def get_sum(self, i, j):
        return self.sum(j) - self.sum(i)
    
    def lower_bound(self, x):#和がx以上になる最小のインデックス
        l, r = 1, self.n
        while r-l > 1:
            index = (r+l)//2
            if self.sum(index) >= x:
                r = index
            else:
                l = index
                
        if self.sum(l) >= x:
            return l
        return r
    
    def upper_bound(self, x):#和がx以下になる最大のインデックス
        if x <= 0:
            return  0
        l, r = 0, self.n
        while r-l > 1:
            index = (r+l)//2
            if self.sum(index) <= x:
                l = index
            else:
                r = index
                
        if self.sum(r) <= x:
            return r
        return l
     

def main():
    q = int(input())
    query = [list(map(int, input().split())) for _ in range(q)]
    
    key = {-10**9}
    for i in range(q):
        if query[i][0] == 1:
            key.add(query[i][1])
    
    key = list(key)
    key.sort()
    n = len(key)
    memo = dict()
    for i, v in enumerate(key):
        memo[v] = i
    
    
    bit = BIT(len(key))
    
    value_min = 0
    
    for i, que in enumerate(query):
        index_min = bit.lower_bound(0)
        
        if que[0] == 2:
            print(key[index_min-1], value_min)
            continue
        
        a, b = que[1:]
        
        value_min += b
        index = memo[a]
        
        l = r = key[index_min-1]
        if index_min != n and bit.sum(index_min) == bit.sum(index_min+1):
            r = key[index_min+1]
        
        if a <= l:
            value_min += l-a
        if r <= a:
            value_min += a-r
        
        
        bit.subtract(1, 1)
        bit.add(index+1, 2)

    
    
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from heapq import heappop, heappush

q = int(input())
ans = 0

mid_1 = 0
mid_2 = 0
mid = 0
left_q = []
right_q = []
left_sum = 0
right_sum = 0
const_b = 0
ansl = []

first_flag = True
double_mid = False
for _ in range(q):
    row = list(input().split())
    if row[0] == '2':
        half_n = len(left_q)
        if double_mid:
            q_left_sum = mid_1*half_n - left_sum
            q_right_sum = right_sum - mid_1*half_n
            ans_v = q_left_sum + q_right_sum + (mid_2-mid_1) + const_b
            ans_x = mid_1
            ansl.append((ans_x, ans_v))
        else:
            q_left_sum = mid*half_n - left_sum
            q_right_sum = right_sum - mid*half_n
            ans_v = q_left_sum + q_right_sum + const_b
            ans_x = mid
            ansl.append((ans_x, ans_v))
    
    else:
        a,b = int(row[1]), int(row[2])
        const_b += b

        if first_flag:
            mid = a
            first_flag = False

        elif double_mid:
            double_mid = False
            if a <= mid_1:
                heappush(left_q, a*(-1))
                left_sum += a
                heappush(right_q, mid_2)
                right_sum += mid_2
                mid = mid_1
            elif a >= mid_2:
                heappush(left_q, mid_1*(-1))
                left_sum += mid_1
                heappush(right_q, a)
                right_sum += a
                mid = mid_2
            else:
                heappush(left_q, mid_1*(-1))
                left_sum += mid_1
                heappush(right_q, mid_2)
                right_sum += mid_2
                mid = a
            print(left_q, mid, right_q)
            print(left_sum, right_sum)


        else:
            double_mid = True
            if a <= mid:
                heappush(left_q, a*(-1))
                left_sum += a
                mid_1 = heappop(left_q)*(-1)
                left_sum -= mid_1
                mid_2 = mid
            else:
                heappush(right_q, a)
                right_sum += a
                mid_1 = mid
                mid_2 = heappop(right_q)
                right_sum -= mid_2
            print(left_q, mid_1, mid_2, right_q)
            print(left_sum, right_sum)



for ax,av in ansl:
    print(ax,av)