Problem:


Score : 700 points

Problem Statement

We will define the median of a sequence b of length M, as follows:

Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.

For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.

Snuke comes up with the following problem.

You are given a sequence a of length N.
For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a.
We will list m_{l, r} for all pairs (l, r) to create a new sequence m.
Find the median of m.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the median of m.

Sample Input 1

3
10 30 20

Sample Output 1

30

The median of each contiguous subsequence of a is as follows:

The median of (10) is 10.

The median of (30) is 30.

The median of (20) is 20.

The median of (10, 30) is 30.

The median of (30, 20) is 30.

The median of (10, 30, 20) is 20.

Thus, m = (10, 30, 20, 30, 30, 20) and the median of m is 30.

Sample Input 2

1
10

Sample Output 2

10

Sample Input 3

10
5 9 5 9 8 9 3 5 4 3

Sample Output 3

8



Sample input:
3
10 30 20


Sample output:
30

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from sys import stdin
import math
import numpy as np

d_in = lambda: int(stdin.readline())  # N = d_in()
ds_in = lambda: list(map(int, stdin.readline().split()))  # List = ds_in()


class SegmentTree(object):
    """
    区分和をSegmentTreeで求める

    Prameters
    ---------
    a_list : list
        対象の配列

    Attributes
    ----------
    n_tree : int
        len(a_list) を超える最小の2べきの数

    tree : list, shape = [2*n_tree - 1]
        セグメント木

    参考URL:
    https://www.slideshare.net/iwiwi/ss-3578491
    http://tsutaj.hatenablog.com/entry/2017/03/29/204841
    """
    def __init__(self, a_list):
        self.n_tree = 2 ** math.ceil(math.log2(len(a_list)))
        self.tree = self.initialize_tree(self.n_tree)

    def initialize_tree(self, n):
        """ tree initialization """
        tree = [0 for _ in range(2*n - 1)]
        return tree

    def update(self, i):
        """ update a_i += 1 """
        idx = self.n_tree + i - 1
        self.tree[idx] += 1
        while idx > 0:
            idx = (idx - 1) // 2
            self.tree[idx] = self.tree[idx*2 + 1] + self.tree[idx*2 + 2]

    def query(self, a, b, k, left, right):
        """
        Get summation value of range [a, b)
        Usage : query(a, b, 0, 0, n_tree)
        """
        if (right <= a) or (left >= b):
            return 0
        elif (left >= a) and (right <= b):
            return self.tree[k]
        else:
            val_left = self.query(a, b, k*2 + 1, left, (left + right) // 2)
            val_right = self.query(a, b, k*2 + 2, (left + right) // 2, right)
            return val_left + val_right


def calc_inversion_num(x, a_list):
    n_a = len(a_list)
    transformed = np.zeros(n_a)
    transformed[a_list < x] = -1
    transformed[transformed != -1] = 1

    cum_t = transformed.cumsum()
    filtered_t = list(sorted(set(cum_t)))
    st = SegmentTree([0] * len(filtered_t))

    inv = (transformed == -1).sum()
    for i, c in enumerate(cum_t):
        temp_inv = st.query(0, filtered_t.index(c)+1, 0, 0, st.n_tree)
        st.update(filtered_t.index(c))
        inv += i - temp_inv

    return inv


N = d_in()
a_list = ds_in()
a_list = np.array(a_list)
sorted_a = np.sort(a_list)

search_range = [0, N]  # range [0, N)
while search_range[1] - search_range[0] > 1:
    mid = (search_range[0] + search_range[1]) // 2
    inv = calc_inversion_num(sorted_a[mid], a_list)
    if (N * (N+1) / 2 - inv) < math.ceil(N * (N+1) / 4):
        search_range[1] = mid
    else:
        search_range[0] = mid

print(sorted_a[search_range[0]])

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from sys import stdin
import math
import numpy as np

d_in = lambda: int(stdin.readline())  # N = d_in()
ds_in = lambda: list(map(int, stdin.readline().split()))  # List = ds_in()


class SegmentTree(object):
    """
    区分和をSegmentTreeで求める

    Prameters
    ---------
    a_list : list
        対象の配列

    Attributes
    ----------
    n_tree : int
        len(a_list) を超える最小の2べきの数

    tree : list, shape = [2*n_tree - 1]
        セグメント木

    参考URL:
    https://www.slideshare.net/iwiwi/ss-3578491
    http://tsutaj.hatenablog.com/entry/2017/03/29/204841
    """
    def __init__(self, a_list):
        self.n_tree = 2 ** math.ceil(math.log2(len(a_list)))
        self.tree = self.initialize_tree(self.n_tree, a_list)

    def initialize_tree(self, n, a_list):
        """ tree initialization """
        tree = [0 for _ in range(2*n - 1)]
        for i in range(len(a_list)):
            tree[n + i - 1] = a_list[i]
        for i in range(n-2, -1, -1):
            tree[i] = tree[2*i + 1] + tree[2*i + 2]
        return tree

    def update(self, i):
        """ update a_i += 1 """
        idx = self.n_tree + i - 1
        self.tree[idx] += 1
        while idx > 0:
            idx = (idx - 1) // 2
            self.tree[idx] = self.tree[idx*2 + 1] + self.tree[idx*2 + 2]

    def query(self, a, b, k, left, right):
        """
        Get summation value of range [a, b)
        Usage : query(a, b, 0, 0, n_tree)
        """
        if (right <= a) or (left >= b):
            return 0
        elif (left >= a) and (right <= b):
            return self.tree[k]
        else:
            val_left = self.query(a, b, k*2 + 1, left, (left + right) // 2)
            val_right = self.query(a, b, k*2 + 2, (left + right) // 2, right)
            return val_left + val_right


def calc_inversion_num(x, a_list):
    n_a = len(a_list)
    transformed = np.zeros(n_a)
    transformed[a_list < x] = -1
    transformed[transformed != -1] = 1

    cum_t = transformed.cumsum()
    filtered_t = list(sorted(set(cum_t)))
    st = SegmentTree([0] * len(filtered_t))

    inv = (transformed == -1).sum()
    for i, c in enumerate(cum_t):
        temp_inv = st.query(0, filtered_t.index(c)+1, 0, 0, st.n_tree)
        st.update(filtered_t.index(c))
        inv += i - temp_inv

    return inv


N = d_in()
a_list = ds_in()
a_list = np.array(a_list)
sorted_a = np.sort(a_list)

search_range = [0, N]  # range [0, N)
while search_range[1] - search_range[0] > 1:
    mid = (search_range[0] + search_range[1]) // 2
    inv = calc_inversion_num(sorted_a[mid], a_list)
    if (N * (N+1) / 2 - inv) < math.ceil(N * (N+1) / 4):
        search_range[1] = mid
    else:
        search_range[0] = mid

print(sorted_a[search_range[0]])

Submission status: Time Limit Exceeded

Solution code:
import sys
global data
global n
global kijun
global a


def merge(list1,_list,count):
    i=0
    j=0
    result=[]
    while(1):
        if(_list[j]<list1[i]):
            result.append(_list[j])
            j+=1
            if(len(_list)<=j):
                return result + list1[i:]
        else:
            result.append(list1[i])
            count[0]+=len(_list)-j
            i+=1
            if(len(list1)<=i):
                return result + _list[j:]
#countはリスト.count[0]がtotalでの交換回数を表す
def merge_sort(_list,count):
    if(len(_list)<=1):
        return _list

    return merge(merge_sort(_list[0:len(_list)//2],count),merge_sort(_list[len(_list)//2:],count),count)

def reverse_num(_list):
    count=[0]
    merge_sort(_list,count)
    return count[0]



def get(_min,_max):
    if(_min==_max):
        return _min
    tmp=1+(_min + _max)//2
    tmp_data=[(data[i]-tmp+0.1)//abs(data[i]-tmp+0.1) for i in range(n)]

    ruiseki=[0.0]
    for i in range(n):
        ruiseki.append(ruiseki[i] + tmp_data[i])

    if(kijun<=reverse_num(ruiseki)):
        return get(tmp,_max)
    else:
        return get(_min,tmp-1)
    
a=0
n=int(input())
data=list(map(int,input().split()))
#kijun個以上、自分以上の数が含まれてれば良い
kijun=((n*(n+1)//2)+1)//2
print(get(min(data),max(data)))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
m = []
for l in range(n):
    for r in range(l, n):
        b = a[l:r+1]
        m.append(b[len(b)//2])
m.sort()
print(m[len(m)//2])

Submission status: Time Limit Exceeded

Solution code:
import math
n = int(input())
l = list(map(int, input().split()))
mlist = []
for i in range(len(l)):
  for j in range(i+1,len(l)+1):
    nums = l[i:j]
    nums.sort()
    mlist.append(nums[math.floor(len(nums)/2)])
mlist.sort()
print(mlist[math.floor(len(mlist)/2)])

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=list(map(int,input().split()))
def median(a):
  b=sorted(a)
  return b[len(a)//2]
med=[]
for l in range(n):
  for r in range(l,n):
    med.append(median(a[l:r+1]))
print(median(med))

Submission status: Time Limit Exceeded

Solution code:
from math import floor

N = int(input())
numbers = list(map(int, input().split()))
medians = []

x = 1
while x != N:
    x += 1
    for i in range(N):
        combo = numbers[i:i+x]
        if len(combo) == x:
            combo.sort()
            m = floor(x/2)
            medians.append(combo[m])

numbers.extend(medians)
numbers.sort()
m = floor(len(numbers)/2)
print(numbers[m])

Submission status: Time Limit Exceeded

Solution code:
#
#  107_D - Median of Medians
#


# 配列の中央に中央値がある数列を返す
def medianSearch(x, posIdx):

	smallerList = [a for a in x[1:] if a <= x[0]]
	largerList = [a for a in x[1:] if a > x[0]]
	smallerListlen = len(smallerList)
	median = 0

	if smallerListlen < posIdx:
		median = medianSearch(largerList, posIdx-smallerListlen-1)
	elif smallerListlen == posIdx:
		median = x[0]
	else:
		median = medianSearch(smallerList, posIdx)

	return median



num = int(input())
numList = [int(x) for x in input().split()]
numPartList = []
medianList = []

for i in range(num):
	for j in range(i+1, num+1):
		numPartList.append(numList[i:j])

for i in numPartList:
	median = medianSearch(i, len(i)//2)
	medianList.append(median)

print(medianSearch(medianList, len(medianList)//2))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))

def count_inversion(input_array):
    n = max(input_array)
    s = [0 for _ in range(n + 2)]

    def bit_add(i):
        x = i
        while x < n:
            s[x] += 1
            x += x & -x

    def bit_sum(i):
        #print(i, s)
        x = i
        ret = 0
        while x > 0:
            ret += s[x]
            x -= x & -x
        #print("ret", ret)
        return ret

    res = 0
    for i in range(len(input_array)):
        x = input_array[i]
        res += i - bit_sum(x)
        bit_add(x)
    return res

b = list(sorted(set(a)))

m = n * (n + 1) // 4 + 1

ans = len(b) // 2

l = 0
r = len(b) - 1
#print(b, m)
while 1:
    s = [n for _ in range(n)]
    s[0] = n
    for i in range(1,n):
        if a[i] >= b[ans]:
            s[i] = s[i - 1] + 1
        else:
            s[i] = s[i - 1] - 1
    base = min(s)
    for i in range(n):
        s[i] -= base - 1
    #print(s, count_inversion(s), l, r, ans)
    if count_inversion(s) > m:
        if ans == l:
            break
        elif ans == l + 1:
            ans = l
            break
        else:
            r = ans
            ans = l + (ans - l) // 2
    else:
        if ans == r:
            break
        else:
            l = ans
            ans = ans + (r - ans) // 2 + 1

print(b[ans])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
src = list(map(int,input().split()))

cands = list(sorted(set(src)))

def enough(i):
    bit = [0] * (2*N+10)
    def bit_add(a,w):
        x = a
        while x <= (2*N+9):
            bit[x] += w
            x += (x & -x)
    def bit_sum(a):
        x = a
        ret = 0
        while x > 0:
            ret += bit[x]
            x -= (x & -x)
        return ret

    cums = [0]
    for a in src:
        tmp = 1 if a >= cands[i] else -1
        cums.append(cums[-1] + tmp)

    cnt = 0
    for i in range(N+1):
        a = cums[i] + N+5
        cnt += bit_sum(a)
        bit_add(a, 1)
    return cnt*2 >= N*(N+1)//2

ok = 0
ng = len(cands)
while ng - ok > 1:
    m = (ok+ng)//2
    if enough(m):
        ok = m
    else:
        ng = m
print(cands[ok])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
src = list(map(int,input().split()))

def enough(n):
    bit = [0] * (2*N+10)
    def bit_add(a,w):
        x = a
        while x <= (2*N+9):
            bit[x] += w
            x += (x & -x)
    def bit_sum(a):
        x = a
        ret = 0
        while x > 0:
            ret += bit[x]
            x -= (x & -x)
        return ret

    cums = [0]
    for a in src:
        tmp = 1 if a >= n else -1
        cums.append(cums[-1] + tmp)

    cnt = 0
    for i in range(N+1):
        a = cums[i] + N+5
        cnt += bit_sum(a)
        bit_add(a, 1)
    return cnt*2 >= N*(N+1)//2

ok = 0
ng = 10**9+1
while ng - ok > 1:
    m = (ok+ng)//2
    if enough(m):
        ok = m
    else:
        ng = m
print(ok)

Submission status: Time Limit Exceeded

Solution code:
import sys
s = sys.stdin.readlines()

N = int(s[0])
A = [int(i) for i in s[1].split()]
A.sort()

def checkMM(num):
    B = [~-((num<=a)<<1) for a in A]
    C = [0]
    [C.append(C[-1]+b) for b in B]
    tmp = 0
    for l in range(N):
        r_l = l+1
        r_r = N
        while r_l != r_r:
            if C[l]<=C[(r_l+r_r)//2]:
                r_r = (r_l+r_r)//2
            else:
                r_l = (r_l+r_r)//2 + 1
        tmp += N - r_r + 1
    return N * (N+1) / 4 < tmp

l = 0
r = N-1
while l != r:
    if checkMM(A[(l+r)//2]):
        l = (l+r)//2 + 1
    else:
        r = (l+r)//2
print(A[r])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [int(i) for i in input().split()]
A.sort()

def checkMM(num):
    B = [~-((num<=a)<<1) for a in A]
    C = [0]
    [C.append(C[-1]+b) for b in B]
    tmp = 0
    for l in range(N):
        r_l = l+1
        r_r = N
        while r_l != r_r:
            if C[l]<=C[(r_l+r_r)//2]:
                r_r = (r_l+r_r)//2
            else:
                r_l = (r_l+r_r)//2 + 1
        tmp += N - r_r + 1
    return N * (N+1) / 4 < tmp

l = 0
r = N-1
while l != r:
    if checkMM(A[(l+r)//2]):
        l = (l+r)//2 + 1
    else:
        r = (l+r)//2
print(A[r])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))

def count_inversion(input_array):
    n = len(input_array)
    s = [0 for _ in range(2 * n + 2)]
    res = 0
    for a in input_array:
        s[a + n] += 1
        res += sum(s[a + n + 1:])
    return res

b = list(sorted(set(a)))

m = n * (n + 1) // 4 + 1

ans = len(b) // 2

l = 0
r = len(b) - 1

while 1:
    s = [0 for _ in range(n)]
    s[0] = 0
    for i in range(1,n):
        if a[i] >= b[ans]:
            s[i] = s[i - 1] + 1
        else:
            s[i] = s[i - 1] - 1
    if count_inversion(s) > m:
        if ans == l:
            break
        elif ans == l + 1:
            ans = l
            break
        else:
            r = ans
            ans = l + (ans - l) // 2
    else:
        if ans == r:
            break
        else:
            l = ans
            ans = ans + (r - ans) // 2 + 1

print(b[ans])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))

def count_inversion(input_array):
    return sum(sum(m < n for m in input_array[i + 1:]) for i, n in enumerate(input_array))

b = list(sorted(set(a)))

m = n * (n + 1) // 4 + 1

ans = len(b) // 2

l = 0
r = len(b) - 1

#print(b)

while 1:
    s = [0 for _ in range(n)]
    s[0] = 0
    for i in range(1,n):
        if a[i] >= b[ans]:
            s[i] = s[i - 1] + 1
        else:
            s[i] = s[i - 1] - 1
    #print(l, ans, r, count_inversion(s))
    if count_inversion(s) > m:
        if ans == l:
            break
        elif ans == l + 1:
            ans = l
            break
        else:
            r = ans
            ans = l + (ans - l) // 2
    else:
        if ans == r:
            break
        else:
            l = ans
            ans = ans + (r - ans) // 2 + 1

print(b[ans])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))

def count_inversion(input_array):
    return sum(sum(m < n for m in input_array[i + 1:]) for i, n in enumerate(input_array))

b = list(reversed(sorted(set(a))))

m = n * (n + 1) // 4 + 1

for ans in b:
    s = [0 for _ in range(n)]
    s[0] = 0
    for i in range(1,n):
        if a[i] >= ans:
            s[i] = s[i - 1] + 1
        else:
            s[i] = s[i - 1] - 1
    if count_inversion(s) <= m:
        print(ans)
        break

Submission status: Time Limit Exceeded

Solution code:
import statistics

def median(b):
  if len(b) % 2 == 0:
    return statistics.median_high(b)
  return statistics.median(b)

n = int(input())
a = list(map(int, input().split()))

m = []
for l in range(n):
  for r in range(n):
    if l <= r:
      m.append(median(a[l:r+1]))

print(median(m))

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))

m = []
for i in range(n):
    m.insert(bisect_left(m, a[i]), a[i])
    b = [a[i]]
    c = 1
    for r in range(i + 1, n):
        b.insert(bisect_left(b, a[r]), a[r])
        c += 1
        temp = b[c // 2]
        m.insert(bisect_left(m, temp), temp)

print(m[((n + 1) * n) // 4])

Submission status: Time Limit Exceeded

Solution code:
import math

def median(b, ln):
  b.sort()
  return b[math.floor(ln/2)]

n = int(input())
a = list(map(int, input().split()))

m = []
for l in range(n):
  for r in range(n):
    if l <= r:
      m.append(median(a[l:r+1], r-l+1))

print(median(m, n*(n+1)/2))

Submission status: Time Limit Exceeded

Solution code:
def median(b):
  b.sort()
  return b[int(len(b)/2)]

n = int(input())
a = list(map(int, input().split()))

m = []
for l in range(n):
  for r in range(n):
    if l <= r:
      m.append(median(a[l:r+1]))

print(median(m))

Submission status: Time Limit Exceeded

Solution code:
import math

def med(num_list):
    num_list.sort()
    return num_list[math.floor(len(num_list)/2)]

def main():
    N = int(input())

    a = list(map(int, input().split()))
    b = []

    for i in range(0, N):
        for j in range(i, N):
            b.append(med(a[i:j+1]))

    print(med(b))

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
a=list(map(int,input().split()))
b=a
for l in range(N-1):
    for r in range(l+1,N):
        c=a[l:r+1]
        c.sort()
        b.append(c[int(len(c)/2.0)])
b.sort()
print(b[int(len(b)/2.0)])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
item_list = list(map(int, input().split()))

def calculate(li):
  total_num = len(li)
  midle_num = total_num // 2 
  return(sorted(li)[midle_num])

def main():
  midle_list = []
  for i in range(0, N):
    for n in range(i + 1, N + 1):
      midle_list.append(calculate(item_list[i:n]))
  print(calculate(midle_list))

main()

Submission status: Time Limit Exceeded

Solution code:
from array import array
from itertools import islice


def main():
    number_count = int(input())
    number_list = array('L', map(int, input().split()))

    median_list = array('L')
    for left_index, median in enumerate(number_list):
        median_list.append(median)
        small_list, large_list = array('L'), array('L')
        for part_length, right in enumerate(islice(number_list, left_index + 1, None), 1):
            if part_length % 2:
                if right <= median:
                    small_list.append(right)
                else:
                    large_list.append(right)
                    small_list.append(median)
                    median = min(large_list)
                    large_list.remove(median)
            else:
                if right < median:
                    small_list.append(right)
                    large_list.append(median)
                    median = max(small_list)
                    small_list.remove(median)
                else:
                    large_list.append(right)
            median_list.append(median)

    median_count = number_count * (number_count + 1) // 2
    print(sorted(median_list)[median_count // 2])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from array import array
from bisect import insort
from itertools import islice


def main():
    number_count = int(input())
    number_list = array('L', map(int, input().split()))

    median_list = array('L')
    for left_index in range(number_count):
        part = array('L')
        for part_length, right in enumerate(islice(number_list, left_index, None), 1):
            insort(part, right)
            median_list.append(part[part_length // 2])

    median_count = number_count * (number_count + 1) // 2
    print(sorted(median_list)[median_count // 2])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a_list = list(map(int, input().split()))

median_list = list(x for x in a_list)
for i in range(len(a_list) - 1):
    partial_seq = list()
    partial_seq.append(a_list[i])
    for j in range(i+1, len(a_list)):
        partial_seq.append(a_list[j])
        partial_seq.sort()
        median_index = len(partial_seq) // 2
        median_list.append(partial_seq[median_index])

median_list.sort()
index = len(median_list) // 2
print(median_list[index])

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
a=list(map(int, input().split()))
c=[]
for i in range(N):
    for j in range(i+1,N+1):
        b=a[i:j]
        b.sort()
        c.append(b[(j-i)//2])
c.sort()
print(c[len(c)//2])

Submission status: Time Limit Exceeded

Solution code:
# encoding: utf-8
# import time
# t0 = time.time()

N = int(input())
a = list(map(int, input().split()))

dict_count = {}
seq_list = []

# t1 = time.time()
# print("#", t1 - t0)

a_sort = sorted(a) # Nlog(N)
l = 0
r = N - 1
while l < r: # log(N)
    i_m = l + (r - l + 1) // 2
    m = a_sort[i_m]
    a_comp = [2 * int(a[i] >= m) - 1 for i in range(N)] # N
    # accumulation
    acm_list = []
    acm = 0
    for i, ai_comp in enumerate(a_comp): # N
        acm += ai_comp
        acm_list.append(acm)
    # merge sort (divide)
    score = 0
    acm_list_temp = [[item] for item in acm_list]
    while len(acm_list_temp) > 1: # Nlog(N)
        pair = [None] * 2
        state = 0
        acm_list_temp2 = []
        for item in acm_list_temp:
            pair[state] = item
            if state == 0:
                state = 1
                continue
            # if state == 1
            newitem = []
            for i in range(len(pair[0]) + len(pair[1])):
                # count
                if pair[0][0] <= pair[1][0]:
                    newitem.append(pair[0].pop(0))                    
                    score += 1
                else:
                    newitem.append(pair[1].pop(0))
                    score -= 1
                # escape
                if len(pair[0]) < 1:
                    newitem += pair[1]
                    score += len(pair[1])
                    break
                elif len(pair[1]) < 1:
                    newitem += pair[0]
                    score -= len(pair[0])
                    break
                else: continue
            acm_list_temp2.append(newitem)
            state = 0
        else:
            if state == 1: acm_list_temp2.append(item)
        acm_list_temp = list(acm_list_temp2)
    # update l or r
    if score == 0: break
    elif score < 0: r = i_m - 1
    else: l = i_m
    
# ans
# t2 = time.time()
# print("#", t2 - t1)
if l == 0 and r == 0: print(a_sort[0])
else: print(m)

Submission status: Time Limit Exceeded

Solution code:
def cen(a,i,j):
    list=a[i:j+1]
    list.sort()
    return list[(j-i+1)//2]

n=int(input())
a=list(map(int, input().split()))
b=[]
for i in range(0,len(a)):
    for j in range(i,len(a)):
        b.append(cen(a,i,j))
b.sort()
print(b[len(b)//2])

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int,input().split()))

A_sort=sorted(A)
ANSMIN=0
ANSMAX=N-1
cums=[None]*(N+1)

def midup(x):
    cums[0]=0
    for i in range(N):
        if A[i]>=x:
            cums[i+1]=cums[i]+1
        else:
            cums[i+1]=cums[i]-1

    MINS=min(cums)
    MAXS=max(cums)

    #print(MINS,MAXS,cums)

    bitlist=[0 for i in range(MAXS-MINS+2)]#出現個数をbit indexed treeの形でもっておく.

    NUM=0#iまでで,s_k<=s_iとなるものの個数

    for i in range(N+1):
        bitobje=cums[i]-MINS+1
        #print(i,bitobje)

        x=bitobje
        while x!=0:
            NUM+=bitlist[x]
            x-=(x&(-x))

        while bitobje<=MAXS-MINS+1:
            bitlist[bitobje]+=1

            #print(i,bitobje,bitlist)
            
            bitobje+=(bitobje &(-bitobje))

        #print(i,bitlist,NUM)

            

    #print(NUM,cums,bitlist)

    if NUM>=(N+1)*N//2/2:
        return 1
    else:
        return 0





while True:
    candi=A_sort[(ANSMIN+ANSMAX)//2]

    if midup(candi)==1:#中央値がx以上なら1を返す！
        ANSMIN=(ANSMIN+ANSMAX)//2
    else:
        ANSMAX=(ANSMIN+ANSMAX)//2

    if A_sort[ANSMIN]==A_sort[ANSMAX]:
        print(A_sort[ANSMIN])
        break
    if ANSMIN+1==ANSMAX:
        if midup(A_sort[ANSMAX])==1:
            print(A_sort[ANSMAX])
            break
        else:
            print(A_sort[ANSMIN])
            break

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

N = int(input())
a = list(map(int, input().split()))
assert len(a) == N

# 解説を参照
# https://img.atcoder.jp/arc101/editorial.pdf

def mergesort(S, f, t, T=None):
    """f <= i < j <= t かつ S[i] <= S[j] である(i,j)の個数.
       実行後, S[f:t]は整列済みになる."""
    if t - f <= 1:
        return 0

    # 作業スペース
    if T == None:
        T = [0] * len(S)

    mid = (f + t) // 2
    n1 = mergesort(S, f, mid, T)
    n2 = mergesort(S, mid, t, T)

    # マージ
    n = n1 + n2
    i = f
    j = mid
    k = f
    while i < mid:
        if j >= t or S[i] <= S[j]:
            T[k] = S[i]
            i += 1
            n += t - j
        else:
            T[k] = S[j]
            j += 1
        k += 1
    for i in range(f, k):
        S[i] = T[i]
    return n

def n_median_larger_than_or_equal_to(x):
    """aの部分列の中央値のうちx以上のものの個数"""

    # aの要素を -1, 1 に置換したリスト
    b = [-1 if e < x else 1 for e in a]

    # bの累積和
    S = [0]
    for e in b:
        S.append(S[-1] + e)

    # 和が0以上であるbの部分列の個数
    # == i < j and S[i] <= S[j] である(i,j)の個数
    return mergesort(S, 0, len(S))

# 条件を満たす x の最大値を2分探索で探す
lo = 1
hi = max(a)

ncomb = N * (N + 1) // 2    # 部分列の個数

while lo < hi:
    mid = (lo + hi + 1) // 2
    nm = n_median_larger_than_or_equal_to(mid)
    if nm >= (ncomb + 1) // 2:
        lo = mid
    else:
        hi = mid - 1

print(lo)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

N = int(input())
a = list(map(int, input().split()))
assert len(a) == N

# 解説を参照
# https://img.atcoder.jp/arc101/editorial.pdf

def mergesort(S, f, t):
    if t - f <= 1:
        return 0, S[f:t]

    n1, S1 = mergesort(S, f, (f + t) // 2)
    n2, S2 = mergesort(S, (f + t) // 2, t)
    T = []
    n = 0
    i = 0
    j = 0
    while i < len(S1) and j < len(S2):
        if S1[i] <= S2[j]:
            T.append(S1[i])
            i += 1
            n += len(S2) - j
        else:
            T.append(S2[j])
            j += 1
    if i < len(S1):
        T.extend(S1[i:])
    if j < len(S2):
        T.extend(S2[j:])
    return n1 + n2 + n, T

def inversion(S):
    """リストSの転倒数"""
    n, __ = mergesort(S, 0, len(S))
    return n

def n_median_larger_than_or_equal_to(x):
    """aの部分列の中央値のうちx以上のものの個数"""

    # aの要素を -1, 1 に置換したリスト
    b = [-1 if e < x else 1 for e in a]
    # bの累積和
    S = [0]
    for e in b:
        S.append(S[-1] + e)
    # Sの転倒数
    return inversion(S)

# 条件を満たす x の最大値を2分探索で探す
lo = 1
hi = max(a)

ncomb = N * (N + 1) // 2    # 部分列の個数

while lo < hi:
    mid = (lo + hi + 1) // 2
    nm = n_median_larger_than_or_equal_to(mid)
    if nm >= (ncomb + 1) // 2:
        lo = mid
    else:
        hi = mid - 1

print(lo)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
array = list(map(int,input().split(" ")))
array2 = []

for r in range(n):
    for l in range(r,n):
        m_rl = sorted(array[r:l+1])
        array2.append(m_rl[(l+1-r)//2])
array2 = sorted(array2)
med = (int((n+1)*n/2))//2
print(array2[med])

Submission status: Time Limit Exceeded

Solution code:
def main():
    """
    """
    N = int(input())
    *a, = map(int, input().split())

    ans = editorial(N, a)
    ans = TLE(N, a)
    print(ans)


def editorial(N, a):
    """
    """
    ans = 0
    return ans


def TLE(N, a):
    ms = []
    for l in range(N):
        for r in range(l, N):
            seq = a[l:r+1]
            idx = len(seq) // 2
            m = sorted(seq)[idx]
            # print(seq, m)
            ms.append(m)

    ans = sorted(ms)[len(ms) // 2]
    return ans


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def findMed(lis):
    Lis=sorted(lis)
    l=len(Lis)
    return Lis[(l//2)]

N=int(input())
a=list(map(int,input().split()))
#print(a)
#print(findMed(a))
tmp=[]
c=0
while c<N:
    for i in range(N-c):
        t=findMed(a[i:i+c+1])
        tmp.append(t)
    c+=1

print(findMed(tmp))

Submission status: Time Limit Exceeded

Solution code:
import copy

def median(a):
    b = copy.copy(a)
    b.sort()
    return b[len(b)//2]

n = int(input())
a = list(map(int, input().split()))
b = []
for i in range(len(a)):
    for j in range(len(a)-i):
        b.append(median(a[i:i+j+1]))
print(median(b))

Submission status: Time Limit Exceeded

Solution code:
N = int(raw_input())
a = map(int,raw_input().split())
x = []
for i in range(N):
  for j in range(N-i):
    b = a[i:i+j+1]
    b.sort()
    d = len(b) 
    if d%2 == 0:
      e = b[d/2]
    else:
      e = b[(d-1)/2]
    x.append(e)
x.sort()
y = len(x)
if y%2 == 0 :
  z = x[y/2]
else:
  z = x[(y-1)/2]
print z

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))

m = []
for i in range(n):
    m.insert(bisect_left(m, a[i]), a[i])
    b = [a[i]]
    c = 1
    for r in range(i + 1, n):
        b.insert(bisect_left(b, a[r]), a[r])
        c += 1
        temp = b[c // 2]
        m.insert(bisect_left(m, temp), temp)

print(m[((n + 1) * n) // 4])

Submission status: Time Limit Exceeded

Solution code:
# seishin.py
N = int(input())
*A, = map(int, input().split())

def calc(x):
    c = 0
    for a in A:
        if x <= a:
            c += 1
        else:
            c -= 1
        yield c

def solve(x):
    data = [0]*(N+1)
    def add(k, x):
        while k <= N:
            data[k] += x
            k += k & -k
    def get(k):
        s = 0
        while k:
            s += data[k]
            k -= k & -k
        return s
    d = -min(calc(x))+1
    res = N*(N+1)//2
    p = 0
    for c in calc(x):
        res -= get(p+d)
        add(c+d, 1)
        p = c
    return res <= N*(N+1)//4

left = min(A); right = max(A)+1
while left+1 < right:
    mid = (left + right) // 2
    if solve(mid):
        left = mid
    else:
        right = mid
print(left)