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: Time Limit Exceeded

Solution code:
import sys
from bisect import insort


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

    def sum(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

    def debug_print(self):
        print(*('{:5d}'.format(i) for i in range(1, self.size + 1)))
        print(*('{:5d}'.format(self.sum(i)) for i in range(1, self.size + 1)))


Q = int(input())
queries = []
nums = []
for qi, line in enumerate(sys.stdin):
    q = list(map(int, line.split()))
    queries.append(q)
    if len(q) > 1:
        _, a, b = q
        nums.append((a, qi))
nums = sorted(nums)
min_a = nums[0][0]
n = len(nums)
num_d = {num: i for i, num in enumerate(nums)}

bit = Bit(n)
update_count = 0
update_list = []
sum_da = 0
sum_b = 0

for qi, q in enumerate(queries):
    if len(q) == 1:
        k = (update_count - 1) // 2
        x, qj = update_list[k]
        i = num_d[x, qj]
        d = x - min_a
        dn_cnt = (update_count + 1) // 2
        up_cnt = update_count - dn_cnt
        bsi = bit.sum(i + 1)
        up_sum = sum_da - bsi - d * up_cnt
        dn_sum = d * dn_cnt - bsi
        # print('k:{} x:{} i:{} d:{} up:{} dn:{}'.format(k, x, i, d, up_sum, dn_sum))
        res = up_sum + dn_sum + sum_b
        print(x, res)
    else:
        _, a, b = q
        sum_b += b
        update_count += 1
        insort(update_list, (a, qi))
        i = num_d[a, qi]
        d = a - min_a
        bit.add(i + 1, d)
        sum_da += d

Submission status: Time Limit Exceeded

Solution code:
def push_alt(x,a):
    lb = -1
    ub = len(x)
    while ub - lb > 1:
        mid = (ub+lb) // 2
        if x[mid] >= a:
            ub = mid
        else:
            lb = mid
    return x.insert(ub,a)
Q = int(input())
com = list(map(int,input().split()))
a = []
a.append(com[1])
b = com[2]
for i in range(Q-1):
    com = list(map(int,input().split()))
    if com[0] == 1:
        push_alt(a,com[1])
        b += com[2]
    else:
        ans = a[(len(a)-1)//2]
        tmp = 0
        for j in range(len(a)):
            tmp += abs(ans - a[j])
        tmp += b
        print(ans,tmp)

Submission status: Time Limit Exceeded

Solution code:
Q = int(input())
Y = []
D = []
S = [0] * Q
s = 0
for i in range(Q):
    a = list(map(int, input().split()))
    Y.append(a)
    if a[0] == 1:
        D.append(a[1])
        s += a[2]
    S[i] = s

D = sorted(list(set(D)))
INV = {}
for i in range(len(D)):
    INV[D[i]] = i

N = 17
X = [0] * (2**(N+1)-1)
C = [0] * (2**(N+1)-1)

def add(j, x):
    i = 2**N + j - 1
    while i >= 0:
        X[i] += x
        C[i] += 1
        i = (i-1) // 2

def rangeof(i):
    s = (len(bin(i+1))-3)
    l = ((i+1) - (1<<s)) * (1<<N-s)
    r = l + (1<<N-s)
    return (l, r)

def rangesum(a, b, i=0):
    l, r = rangeof(i)
    if l >= b or r <= a:
        return 0
    if a <= l and r <= b:
        return X[i]
    return rangesum(a, b, 2*i+1) + rangesum(a, b, 2*i+2)
def rangecnt(a, b, i=0):
    l, r = rangeof(i)
    if l >= b or r <= a:
        return 0
    if a <= l and r <= b:
        return C[i]
    return rangecnt(a, b, 2*i+1) + rangecnt(a, b, 2*i+2)

c = 0
su = 0
CC = [0] * (2**N)
for i in range(Q):
    y = Y[i]
    if y[0] == 1:
        add(INV[y[1]], y[1])
        CC[INV[y[1]]] += 1
        c += 1
        su += y[1]
    else:
        l, r = 0, 2**N
        while True:
            m = (l+r)//2
            rc = rangecnt(0, m)
            if rc >= (c+1)//2:
                r = m
            elif rc + CC[m] <= (c-1)//2:
                l = m
            else:
                break
        rs = rangesum(0, m)
        print(D[m], D[m]*rc-rs+(su-rs)-(c-rc)*D[m]+S[i])

Submission status: Time Limit Exceeded

Solution code:
import bisect

ql=int(input())
B=0
es=[]
midSep=0
sumOfLefter = 0
sumOfRighter = 0
for qi in range(ql):
    q=tuple(map(int,input().split()))
    if q==(2,):
        midE = es[midSep-1]
        #re = B + (midE*midSep-sumOfLefter + sumOfRighter-midE*midSep)//2
        re = B + (sumOfRighter-sumOfLefter)//2
        print(midE,re)
    else:
        e = q[1]
        b = q[2]
        B += b
        ei = bisect.bisect_left(es,e)
        if ei == midSep:
            sumOfLefter += e
            sumOfRighter += e
        elif ei < midSep:
            sumOfLefter += e*2-es[midSep-1]
            sumOfRighter += es[midSep-1]
        elif ei > midSep:
            sumOfLefter += es[midSep]
            sumOfRighter += e*2-es[midSep]
        es.insert(ei,e)
        es.insert(ei,e)
        midSep+=1

Submission status: Time Limit Exceeded

Solution code:
import bisect
q = int(input())
query = [list(map(int,input().split())) for i in range(q)]
a = []
b = 0
c = 0
 
for i in range(q):
    if query[i][0] == 1:
        bisect.insort(a,query[i][1])
        b += query[i][2]
    else:
        a1 = (len(a)-1) // 2
        a2 = a[a1]
        c = 0
        for j in range(len(a)):
            c += abs(a[j]-a2)
        print(a2,c+b)

Submission status: Time Limit Exceeded

Solution code:
Q = int(input())
LI = []
CO = 0
ans = 0
for i in range(Q):
    L = list(map(int,input().split()))
    if L[0] == 1:
        CO += L[2]
        LI.append(L[1])
        LI.sort()
    else:
        ans = 0
        ans += CO
        for i in range(len(LI)):
            ans += abs(LI[i]-LI[len(LI)//2])
        if len(LI) %2 == 0:
            print(str(LI[len(LI)//2-1])+' '+str(ans))
        else:
            print(str(LI[len(LI)//2])+' '+str(ans))

Submission status: Time Limit Exceeded

Solution code:
import sys
qin = int(raw_input())

p = []
q = []
sum_b = 0
q_count = 0

for i in range(0, qin):
    inp = map(int, raw_input().split(" "))

    if len(inp) == 3:  # 1
        a = inp[1]
        b = inp[2]
        p.append((a, q_count))
        sum_b += b
        q_count += 1

    else: # 2
        q.append((q_count - 1, sum_b))

p = sorted(p, key=lambda (a, n): a)
# print("p: %s" % p)
# print("q: %s" % q)
dp = [[-1 for j in range(0, len(q))] for j in range(0, len(p))]


for qx in range(0, len(q)):
    # print("------")
    qn, sum_b = q[qx]
    min_x_index = int((qn + 1) / 2) - (1 - ((qn + 1) % 2))

    count = -1
    min_x = 0
    for i in range(0, len(p)):
        a, pn = p[i]
        if pn <= qn:
            count += 1

        if min_x_index == count:
            min_x = a
            break
    # print("%d -> %d" % (min_x_index, min_x))

    for px in range(0, len(p)):
        a, pn = p[px]
        if px > 0:
            g, prev = dp[px - 1][qx]
        else:
            prev = sum_b

        if pn <= qn:
            add = abs(min_x - a)
        else:
            add = 0

        dp[px][qx] = (min_x, prev + add)

# print("======")
for i in range(0, len(q)):
    ans = dp[len(p) - 1][i]
    print("%d %d" % ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect
from operator import itemgetter
import math
import functools
import itertools
import numpy as np
import sys
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

Q = I()
data = []

cnt = 0
num = 0
for i in range(Q):
    q = IL()
    if len(q) == 1:
        if cnt%2 == 0:
            tmp = data[(cnt//2)-1]
        else:
            tmp = data[cnt//2]
        ans = 0
        for i in data:
            ans += abs(i-tmp)
        print(tmp,ans+num)
    else:
        bisect.insort_left(data,q[1])
        cnt += 1
        num += q[2]

Submission status: Time Limit Exceeded

Solution code:
import copy
import bisect

q = int(input())

s = []

def q2(e,b):
    counter = 0
    a = copy.deepcopy(e)
    while(a):
        if len(a) == 1:
            point = a.pop(0)
        elif len(a) == 2:
            point = a.pop(0)
            r = a.pop(-1)
            counter += r - point
        else:
            r = a.pop(-1)
            l = a.pop(0)
            counter += r-l
    print(point,counter+b)

k = 0
tlist = []
for i in range(q):
    t = list(map(int,input().split()))
    tlist.append(t)
    
    
for t in tlist:
    if t[0] == 1:
        index = bisect.bisect_left(s, t[1])
        s.insert(index, t[1])
        k+=t[2]
    else:
        q2(s,k)

Submission status: Time Limit Exceeded

Solution code:
# coding:utf-8

import math
import re

def main(params):
    q = params[0]
    queries = params[1:]
    currentB = 0
    listA = []
    for i in queries:
        line = i.split()
        if len(line) > 1:
            code, a, b = i.split()
            code = int(code)
            a = int(a)
            b = int(b)
            currentB += b
            listA.append(a)
        else:
            listA.sort()
            target = len(listA)/2
            if len(listA) % 2 == 0:
                target -= 1
            t = 0
            for j in listA:
                t += abs(listA[target] - j)
            t += currentB
            print listA[target],t


if __name__ == "__main__":
    q = raw_input()
    q = int(q)
    cnt = q # TODO: edit here
    params = [q]
    for i in range(cnt):
        param = raw_input()
        params.append(param)
    main(params)

Submission status: Time Limit Exceeded

Solution code:
Q = int(input())
c = 0
b = 0
a = []
sum_a = 0
sum_a_mae = 0
sum_b = 0
def append_a(n):
	if c == 0:
		a.append(n)
		return
	l,r = 0,c
	while r - l > 1:
		p = (l+r)//2
		if a[p] > n:
			r = p
		else:
			l = p
	if a[l] >= n:
		a.insert(l, n)
	else:
		a.insert(l+1, n)

for i in range(Q):
	s = input()
	if s[0] == '1':
		x,y,z = map(int, s.split())
		if c > 0:
			a_med = a[c//2] if c % 2 == 1 else a[c//2-1]
		else:
			a_med = -10**9
		sum_a += y
		sum_b += z
		append_a(y)
		c += 1
		if c % 2 == 0:
			if y < a_med:
				sum_a_mae += y
			else:
				sum_a_mae += a_med
		else:
			if y < a_med:
				sum_a_mae += y - a_med
	else:
		print(a[c//2 - (1 - c%2)], sum_b + sum_a - 2*sum_a_mae - (c%2) * a[c//2])

Submission status: Time Limit Exceeded

Solution code:
import copy

q = int(input())

s = []

def q2(t,b):
    counter = 0
    a = copy.deepcopy(t)
    a.sort()
    while(a):
        if len(a) == 1:
            point = a.pop(0)
        elif len(a) == 2:
            point = a.pop(0)
            r = a.pop(-1)
            counter += r - point
        else:
            r = a.pop(-1)
            l = a.pop(0)
            counter += r-l
    print(point,counter+b)

k = 0
tlist = []
for i in range(q):
    t = list(map(int,input().split()))
    tlist.append(t)
    
    
for t in tlist:
    if t[0] == 1:
        s.append(t[1])
        k+=t[2]
    else:
        q2(s,k)

Submission status: Time Limit Exceeded

Solution code:
import heapq


Q = int(input())
Alist = []
S = 0
Bsum = 0
Qs = [input() for _ in range(Q)]
for query in Qs:
    if query[0] == "1":
        _, a, b = map(int, query.split(" "))
        Bsum += b
        heapq.heappush(Alist, a)
        S += a
    else:
        key = len(Alist)
        S2 = S
        minx = Alist[0]
        tempAns = S - key * minx
        copyAlist = Alist.copy()
        while len(copyAlist) > 0:
            a = heapq.heappop(copyAlist)
            tempAns2 = S2 - key * a
            if tempAns > tempAns2:
                tempAns = tempAns2
                minx = a
            S2 += - 2 * a
            key -= 2
        tempAns2 = S2 - key * a
        if tempAns > tempAns2:
            tempAns = tempAns2
            minx = a
        print(str(minx) + " " + str(tempAns+Bsum))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

num_q = int(input())
x = 0
f = 0
a = []
c = False
b = 0

for _ in range(num_q):
  q = input()
  if q[0] == '2':
    print(x, f)
  else:
    _, n, m = map(int, q.split(" "))
    a.append(n)
    a.sort()
    x_tmp = a[b//2]
    if c:
      f += m + np.abs(x - n)
    else:
      f += m + np.abs(x_tmp - n)
    c = ~c
    x = x_tmp
    b += 1

Submission status: Time Limit Exceeded

Solution code:
Q = int(input())
A, B = [],[]
ans = 0

for i in range(Q):
    tmp = list(map(int, input().split()))
    if tmp[0] == 1:
        A.append(tmp[1])
        B.append(tmp[2])
    elif tmp[0] == 2:
        for j in range(len(A)):
            x = A[j]
            ans = sum(B)
            for k in range(len(A)):
                ans += (abs(x-A[k]))
        print(x, ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

Q=int(input())

b=0
a=[]
min=0
tmp=0
j=0
for i in range(Q):
    que=list(map(int,input().split()))
    if que[0]==1:
        j+=1
        b+=que[2]
        a.insert(  bisect.bisect_left(a,que[1]), que[1] )

        p= bisect.bisect_left(a,tmp)
        if p>j-p:
            min+=abs(que[1]-tmp)-abs(a[p-1]-tmp) 
            tmp=a[p-1]
        elif p==j-p:
            min+=abs(que[1]-tmp)
            tmp=a[p-1]
        else:
            q= bisect.bisect_right(a,tmp)
            if q<j-q:
                min+=abs(que[1]-tmp)-abs(a[q]-tmp) 
                tmp=a[q]
            else:min+=abs(que[1]-tmp)

    elif que[0]==2:
        print(tmp,min+b)

Submission status: Time Limit Exceeded

Solution code:
from bisect import insort_left

Q = int(input())
a_list = []
scalar = 0
length = 0
for _ in range(Q):
    input_list = list(map(int,input().split()))
    if input_list[0]==1:
        a = input_list[1]
        insort_left(a_list,a)
        scalar += input_list[2]
        length += 1
    else:
        # unique_a_list =list(set(a_list.copy())) 
        if length%2==0:
            ans0_pos =int(length/2 - 1)
            ans0 = a_list[ans0_pos]
            ans1 = -1* sum(a_list[:ans0_pos+1]) + sum(a_list[ans0_pos+1:])+scalar

        else:
            ans0_pos = int(length/2-0.5)
            
            ans0 = a_list[ans0_pos]
            ans1 = -1* sum(a_list[:ans0_pos]) + sum(a_list[ans0_pos+1:]) + scalar
        print(str(ans0)+" "+str(ans1))

Submission status: Time Limit Exceeded

Solution code:
import heapq
import copy
import math

Q = int(input())
A = []
B = 0
for _ in range(Q):
    nums = [int(i) for i in input().split()]
    if nums[0] == 1:
        heapq.heappush(A, nums[1])
        B += nums[2]
    else:
        copy2 = copy.deepcopy(A)
        copyA = [heapq.heappop(copy2) for i in range(len(A))]
        x = copyA[int(math.floor((len(A) - 1) / 2))]
        res = sum([abs(x - i) for i in A]) + B
        print(x, res)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

import sys
import math

import array
import bisect
import collections
from collections import Counter, defaultdict
import fractions
import heapq
import re

sys.setrecursionlimit(1000000)


def array2d(dim1, dim2, init=None):
    return [[init for _ in range(dim2)] for _ in range(dim1)]

def argsort(l, reverse=False):
    return sorted(range(len(l)), key=lambda i: l[i], reverse=reverse)

def argmin(l):
    return l.index(min(l))

def YESNO(ans, yes="YES", no="NO"):
    print([no, yes][ans])

II = lambda: int(input())
MI = lambda: map(int, input().split())
MIL = lambda: list(MI())
MIT = lambda: tuple(MI())
MIS = lambda: input().split()


class WHeap(object):
    def __init__(self):
        self._heap1 = []
        self._heap2 = []
        self.sum_h1 = 0
        self.sum_h2 = 0

    def __len__(self):
        return len(self._heap1) + len(self._heap2)

    def iter(self):
        for i in self._heap1:
            yield -i
        for i in self._heap2:
            yield i

    def __str__(self):
        return str(self._heap1) + " " + str(self._heap2)

    def push(self, n):
        if len(self) % 2 == 0:
            if not self._heap2 or n <= self._heap2[0]:
                heapq.heappush(self._heap1, -n)
                self.sum_h1 += n
            else:
                d = self._heap2[0]
                heapq.heappush(self._heap1, -heapq.heappop(self._heap2))
                self.sum_h1 += d
                self.sum_h2 -= d
                heapq.heappush(self._heap2, n)
                self.sum_h2 += n
        else:
            if n < -self._heap1[0]:
                d = -self._heap1[0]
                heapq.heappush(self._heap2, -heapq.heappop(self._heap1))
                self.sum_h1 -= d
                self.sum_h2 += d
                heapq.heappush(self._heap1, -n)
                self.sum_h1 += n
            else:
                heapq.heappush(self._heap2, n)
                self.sum_h2 += n

    def med(self):
        return -self._heap1[0]

    def pop(self, n):
        result = self.med()
        if len(self) % 2 == 0:
            heapq.heappop(self._heap1)
            heapq.heappush(self._heap1, -heapq.heappop(self._heap2))
        else:
            heapq.heappop(self._heap1)


def main():
    Q = II()
    wh = WHeap()
    B = 0
    for _ in range(Q):
        query = MIT()
        if query[0] == 1:
            wh.push(query[1])
            B += query[2]
        else:
            x = wh.med()
            if len(wh) % 2 == 0:
                f = - wh.sum_h1 + wh.sum_h2 + B
            else:
                f = x - wh.sum_h1 + wh.sum_h2 + B
            print(x, f)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
rr = lambda: sys.stdin.readline().strip()
rri = lambda: int(rr())
rrs = lambda: [int(_) for _ in rr().split()]

from bisect import insort_left

Q = rri()
avg = 0
a = []
b = 0
c = 0

for _ in range(Q):
    d = rrs()

    if d[0] == 1:
        insort_left(a, d[1])
        b += d[2]
        c = len(a)
        m = -(-c//2)-1
    
    if d[0] == 2:
        ans = b - sum(a[:m]) + sum(a[m:]) - a[m] * (c - m * 2)
        print(a[m], ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

Q=int(input())

b=0
a=[]
min=0
tmp=0
j=0
for i in range(Q):
    que=list(map(int,input().split()))
    if que[0]==1:
        j+=1
        b+=que[2]
        a.insert(  bisect.bisect_left(a,que[1]), que[1] )

        p= bisect.bisect_left(a,tmp)
        q= bisect.bisect_right(a,tmp)
        if p>j-p:
            min+=abs(que[1]-tmp)-abs(a[p-1]-tmp) 
            tmp=a[p-1]
        elif p==j-p:
            min+=abs(que[1]-tmp)
            tmp=a[p-1]

        else:
            q= bisect.bisect_right(a,tmp)
            if q<j-q:
                min+=abs(que[1]-tmp)-abs(a[q]-tmp) 
                tmp=a[q]
            else:min+=abs(que[1]-tmp)

    elif que[0]==2:
        print(tmp,min+b)

Submission status: Time Limit Exceeded

Solution code:
import statistics
Q = int(input())
a = []
b = 0
def f():
  global a,b
  median = statistics.median_low(a)
  ans = b
  for i in a:
    ans += abs(median-i)
  print(median,ans)
for _ in range(Q):
  que = list(map(int,input().split()))
  if que[0]==1:
    a.append(que[1])
    b += que[2]
  else:
    
    f()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat May 25 21:57:15 2019

@author: Yamazaki Kenichi
"""
import bisect

Q = int(input())
Q2 = [input() for i in range(Q)]

ans = []
A = []
B = 0
C = 0
counta = 0
d, prea, b = map(int,Q2[0].split()) 
for q in Q2:
    if q[0] == '1':
#        input
        d, a, b = map(int,q.split()) 
        bisect.insort_left(A,a)
#        if A[(len(A)-1)//2] > a:
#            C = abs(prea - a)
#        else:
#            C = abs(A[(len(A)-1)//2] - a)
        C = abs(A[(len(A)-1)//2] - a) if counta % 2 == 0 else abs(prea - a)
        B += (b + C)
#        C = abs(prea - a)
        prea = A[(len(A)-1)//2]
        counta += 1
    else:
#        output
        tmp = A[(len(A)-1)//2]
        ans.append([tmp,B])
for c in ans:
    print(' '.join(map(str,c)))

Submission status: Time Limit Exceeded

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

q = int(input())
al = []

s = 0
for i in range(q):
    query = input()
    if len(query) > 2:
        que, a, b = map(int, query.split())
        al.append(a)
        s += b
    else:
        al.sort()
        if len(al) % 2 == 1:
            x = al[(len(al) - 1) // 2]
        else:
            x = al[len(al) // 2 - 1]
        ans = sum([abs(x - i) for i in al])
        ans += s
        print(x, ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

q = int(input())
list1 = []
s = 0
for _ in range(q):
    a = list(map(int, input().split()))
    if a[0] == 1:
        s += a[2]
        insert_index = bisect.bisect_left(list1, a[1])
        n = len(list1)
        if n%2 == 0:
            if insert_index > n//2:
                s += a[1]-list1[n//2]
            elif insert_index < n//2:
                s += list1[n//2-1] - a[1]
        else:
            s += abs(list1[n//2]-a[1])
        list1.insert(insert_index, a[1])
            
    else:
        print(list1[n//2], s)

Submission status: Time Limit Exceeded

Solution code:
###############################################################################

from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy
from collections import defaultdict
import heapq


mod = 1


def intin():
    input_tuple = input().split()
    if len(input_tuple) <= 1:
        return int(input_tuple[0])
    return tuple(map(int, input_tuple))


def intina():
    return [int(i) for i in input().split()]


def intinl(count):
    return [intin() for _ in range(count)]


def modadd(x, y):
    global mod
    return (x + y) % mod


def modmlt(x, y):
    global mod
    return (x * y) % mod


def lcm(x, y):
    while y != 0:
        z = x % y
        x = y
        y = z
    return x


def combination(x, y):
    assert(x >= y)

    if y > x // 2:
        y = x - y

    ret = 1

    for i in range(0, y):
        j = x - i
        i = i + 1

        ret = ret * j
        ret = ret // i

    return ret


def get_divisors(x):
    retlist = []
    for i in range(1, int(x**0.5) + 3):
        if x % i == 0:
            retlist.append(i)
            retlist.append(x // i)
    return retlist


def get_factors(x):
    retlist = []
    for i in range(2, int(x**0.5) + 3):
        while x % i == 0:
            retlist.append(i)
            x = x // i
    retlist.append(x)
    return retlist


def make_linklist(xylist):
    linklist = {}
    for a, b in xylist:
        linklist.setdefault(a, [])
        linklist.setdefault(b, [])
        linklist[a].append(b)
        linklist[b].append(a)
    return linklist


def calc_longest_distance(linklist, v=1):
    distance_list = {}
    distance_count = 0
    distance = 0
    vlist_previous = []
    vlist = [v]
    nodecount = len(linklist)

    while distance_count < nodecount:
        vlist_next = []
        for v in vlist:
            distance_list[v] = distance
            distance_count += 1
            vlist_next.extend(linklist[v])
        distance += 1
        vlist_to_del = vlist_previous
        vlist_previous = vlist
        vlist = list(set(vlist_next) - set(vlist_to_del))

    max_distance = -1
    max_v = None
    for v, distance in distance_list.items():
        if distance > max_distance:
            max_distance = distance
            max_v = v

    return (max_distance, max_v)


def calc_tree_diameter(linklist, v=1):
    _, u = calc_longest_distance(linklist, v)
    distance, _ = calc_longest_distance(linklist, u)
    return distance


class UnionFind:

    def __init__(self, n):
        self.parent = [i for i in range(n)]

    def root(self, i):
        if self.parent[i] == i:
            return i
        self.parent[i] = self.root(self.parent[i])
        return self.parent[i]

    def unite(self, i, j):
        rooti = self.root(i)
        rootj = self.root(j)
        if rooti == rootj:
            return
        if rooti < rootj:
            self.parent[rootj] = rooti
        else:
            self.parent[rooti] = rootj

    def same(self, i, j):
        return self.root(i) == self.root(j)


###############################################################################


def main():
    qnum = intin()
    qlist = [input() for _ in range(qnum)]

    alist = []
    acount = 0
    lsum = 0
    rsum = 0
    bsum = 0

    for q in qlist:

        if q[0] == '1':
            q = q.split(' ')
            a = int(q[1])
            b = int(q[2])

            bsum += b

            med = None
            odd_slice = None
            even_slice = None

            if alist:
                med = alist[acount//2 if acount&1 else acount//2-1]
                if acount & 1:
                    if a <= med:
                        odd_slice = True
                    else:
                        odd_slice = False
                else:
                    if a < med:
                        even_slice = False
                    else:
                        even_slice = True

            heapq.heappush(alist, a)
            alist.sort()
            acount += 1

            if med is not None:
                prev_med = med
                med = alist[acount//2 if acount&1 else acount//2-1]
                if odd_slice is not None:
                    if odd_slice:
                        lsum -= (abs(prev_med - med) * ((acount - 1) // 2))
                        lsum += abs(med - a)
                        rsum += (abs(prev_med - med) * (acount // 2))
                    else:
                        rsum += abs(med - a)
                if even_slice is not None:
                    if even_slice:
                        lsum += (abs(med - prev_med) * (acount // 2))
                        rsum -= (abs(med - prev_med) * (acount // 2))
                        rsum += abs(a - med)
                    else:
                        lsum += abs(med - a)

        if q[0] == '2':
            print('%d %d' % 
                  (alist[acount//2 if acount&1 else acount//2-1],
                   lsum + rsum + bsum))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
import bisect
q=int(input())
h=[]
b=0 #bの和
s=0 #絶対偏差の和
med=0
for _ in range(q):
    Tmp=tuple(map(int,input().split()))
    if Tmp[0]==1:
        b+=Tmp[2]
        if len(h)%2:
            s+=abs(Tmp[1]-med)
        else:
            if h:
                med_next=h[(len(h)-1)//2+1]
                if Tmp[1]<=med:
                    s+=abs(Tmp[1]-med)
                elif Tmp[1]>=med_next:
                    s+=abs(Tmp[1]-med_next)
            else:
                med=Tmp[1]
        bisect.insort(h,Tmp[1])
        med=h[(len(h)-1)//2]
    else:
        print(med,s+b)

Submission status: Time Limit Exceeded

Solution code:
import bisect

def cul(a,b,n):
    if len(a)%2==1:
        ans=-sum(a[:n])+sum(a[n+1:])
    else:
        ans=-sum(a[:n+1])+sum(a[n+1:])
    return ans+b

q=int(input())
b=0
a=[]
for i in range(q):
    p=input()
    if p=="2":
        l=len(a)
        if l%2==1:
            n=l//2
            m=a[n]
        else:
            n=l//2-1
            m=a[n]
        print(m,cul(a,b,n))
        
    else:
        cq,ai,bi=map(int,p.split())
        b+=bi
        index = bisect.bisect_left(a, ai)
        a.insert(index, ai)

Submission status: Time Limit Exceeded

Solution code:
import sys
rr = lambda: sys.stdin.readline().strip()
rri = lambda: int(rr())
rrs = lambda: [int(_) for _ in rr().split()]

from bisect import insort_left

Q = rri()
avg = 0
a = []
b = 0
c = 0

for _ in range(Q):
    d = rrs()

    if d[0] == 1:
        insort_left(a, d[1])
        b += d[2]
        c = len(a)
        m = -(-c//2)-1
    
    if d[0] == 2:
        ans = b
        ans += -sum(a[:m]) + sum(a[m:]) - a[m] * (c - m * 2)
        print(a[m], ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

Q=int(input())

b=0
a=[]
min=0
tmp=0
j=0
for i in range(Q):
    que=list(map(int,input().split()))
    if que[0]==1:
        j+=1
        b+=que[2]
        a.insert(  bisect.bisect_left(a,que[1]), que[1] )

        p= bisect.bisect_left(a,tmp)
        q= bisect.bisect_right(a,tmp)
        if p>j-p:
            min+=abs(que[1]-tmp)-abs(a[p-1]-tmp) 
            tmp=a[p-1]
        elif p==j-p:
            min+=abs(que[1]-tmp)
            tmp=a[p-1]
        elif q<j-q:
            min+=abs(que[1]-tmp)-abs(a[q]-tmp) 
            tmp=a[q]
        else:

            min+=abs(que[1]-tmp)

    elif que[0]==2:
        print(tmp,min+b)

Submission status: Time Limit Exceeded

Solution code:
import bisect
Q = int(input())
A = []
sumb = 0
N = 0
ans = []
for i in [0]*Q:
	inp = list(map(int,input().split(' ')))
	if inp[0] == 1:
		N += 1
		a,b = inp[1:]
		sumb += b
		bisect.insort(A,a)
	else:
		n = -(-N//2)-1
		x = A[n]
		s = 0
		t = 0
		if N > 2:
			s = x*n-sum(A[:n])
			t = sum(A[n+1:]) - x*(N-(n+1))
		elif N > 1:
			s = 0
			t = sum(A[n+1:]) - x*(N-(n+1))
		ans.append((x,s+t+sumb))

for i in ans:
	print(i[0],i[1])

Submission status: Time Limit Exceeded

Solution code:
import statistics

n = int(input())
l = [list(int(_) for _ in input().split()) for i in range(n)]
x = [i[1] for i in l if i[0] == 1]
y = [i[2] for i in l if i[0] == 1]
z = [i for i in range(len(l)) if l[i][0] == 2]
z = [z[i] -i for i in range(len(z))]

for i in z:
    s = statistics.median_low(x[:i])
    print(s,sum([abs(i-s) for i in x[:i]])+sum(y[:i]))

Submission status: Time Limit Exceeded

Solution code:
Q = int(input())

aList = []
sumA = 0
sumB = 0
N = 0

for i in range(Q):
    Query = list(map(int,input().split()))
    if Query[0] == 1:
        sumB += Query[2]
        a = Query[1]
        aList.append(Query[1])
        sumA += a
        N += 1
    else:
        aList.sort()
        mean = (N + 1) // 2 - 1
        ans1 = aList[mean]
        if N % 2 == 1:
            ans2 = sumB + sumA - sum(aList[:mean]) * 2 - aList[mean]
        else:
            ans2 = sumB + sumA - sum(aList[:(mean + 1)]) * 2
        print("{} {}".format(ans1, ans2))