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: Wrong Answer

Solution code:
n = int(raw_input())
lis = map(int, raw_input().split())
lis = sorted(lis)
val = ((n*(n+1))/2)
idx = (val/2)+1
summ=0
z=1
#print idx
#print lis
for i in xrange(n):
    summ+=(z)
    z+=1
    #print summ
    if summ>idx:
        #print idx
        print lis[i]
        break

Submission status: Wrong Answer

Solution code:
import statistics

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

l = []

if n > 100:
    a = a[n//2-50:n//2+50]

for i in range(len(a)):
    for j in range(i,len(a)):
        l.append(statistics.median_high(a[i:j+1]))

print(statistics.median_high(l))

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
lis = map(int, raw_input().split())
lis = sorted(lis)
val = ((n*(n+1))/2)
idx = (val/2)+1
summ=0
z=1
#print idx
#print lis
for i in xrange(n):
    summ+=(z)
    z+=1
    #print summ
    if summ==idx:
        #print idx
        print lis[i]
        break

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
lis = map(int, raw_input().split())
lis = sorted(lis)
val = ((n*(n+1))/2)
idx = (val/2)+1
summ=0
z=1
#print idx
#print lis
for i in xrange(n):
    summ+=(z)
    z+=1
    #print summ
    if summ==idx:
        #print idx
        print lis[i]
        break
    elif summ==idx-1:
        print lis[i+1]
        break

Submission status: Wrong Answer

Solution code:
from math import ceil
n=int(input())
a=sorted([int(i) for i in input().split()])
if n==1:
  print(a[0])
elif n % 2 == 1:
  print(a[ceil(n/2)])
else:
  print(a[ceil(n/2)-1])

Submission status: Wrong Answer

Solution code:
n=int(input())
c=0
g=0
bg=0
hk=sum([i for i in range(1,n+1)])//2+1
while c<n:
   g+=n-c
   c+=1
   if g>=hk:
      z=hk-bg
      q=list(map(int,input().split()))[z-1:z+c-1]
      print(sorted(q)[len(q)//2])
      break
   bg=g

Submission status: Wrong Answer

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

a.sort()
mid = (N * (N + 1) / 2) // 2

num = 0
while 1:
    num += 1
    move = (num * (num + 1) / 2)
    if move > mid:
        break

print(a[num - 1])

Submission status: Wrong Answer

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

if n % 2 == 1:
    print(a[n//2])
else:
    print(a[n//2 - 1])

Submission status: Wrong Answer

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

a.sort()
mid = (N * (N + 1) / 2) // 2

num = 0
while 1:
    num += 1
    move = (num * (num + 1) / 2)
    if move >= mid:
        break

print(a[num - 1])

Submission status: Wrong Answer

Solution code:
input()
a=sorted(set(map(int,input().split())))
if len(a)==1:
    print(*a)
else:
    print(a[len(a)//2+1])

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 18 00:01:41 2018

@author: Yuya
"""

n = int(input())

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


now = 1

x = []

for i in range((n+1)//2):
    x.append(now)
    now +=2

now = (n//2)*2

for i in range((n+1)//2, n):
    x.append(now)
    now -=2

ans = []

for i in range(n):
    ans.append([a[i], x[i]])
    
ans.sort()

now = 0

for i in range(n):
    now += ans[i][1]
    if now>(n*(n+1)//2)//2+1:
        break

print(ans[i][0])

Submission status: Wrong Answer

Solution code:
print(20)

Submission status: Wrong Answer

Solution code:
print(10)

Submission status: Wrong Answer

Solution code:
n=int(input())
nums=[int(x) for x in input().split()]

def findMedian(nums):
    size=len(nums)
    mIndex = (size*(size+1)//2) + 1
    gap=0
    mValue=0
    while mIndex>0 and gap<size:
        start=0
        end=start+gap
        while end<size and mIndex>0:
            mIndex-=1
            mValue=nums[(start+end+1)//2]
            start+=1
            end+=1
        gap+=1
    return mValue

print(findMedian(nums))

Submission status: Wrong Answer

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

for i in range(N-1):
    A.append(max(A[i],A[i+1]))

A.sort()
N=len(A)

if N%2==1:
    print(A[N//2])
else:
    print(A[N//2-1])

Submission status: Wrong Answer

Solution code:
N = int(input())
array = list(map(int, input().split()))
array.insert(0, 0)
mid = int(N//2 + 1)
length = N * (N+1) / 2
middle = int(length//2 + 1)
another = [[0,0]]

count = 0
result = None
for i in range(1, N+1):
    if 2*i - 1 <= N:
        temp = 2*i - 1
    elif i == mid:
        temp = N
    elif i > mid:
        temp = (N - i + 1)*2
    another.append([array[i], temp])

another.sort()

for i in range(1, N+1):
    count += another[i][1]
    if count >= middle:
        result = i
        break
    
print(another[result][0])

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout

input = lambda: stdin.readline()
write = stdout.write

def main():
    N = int(input())
    A = tuple(map(int, input().split()))

    if N % 2:
        i = N // 2
    else:
        i = N // 2 - 1
    print(A[i])

main()

Submission status: Wrong Answer

Solution code:
N = int(input())
a = list(map(int, input().split()))
 
print(a[N // 2- (N+1)% 2])

Submission status: Wrong Answer

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

# print(n,k)
m = (n+1)//2
print(a[m-1])

Submission status: Wrong Answer

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

AA=sorted(A)

if N%2==1:
    if AA[N//2]>A[N//2]:
        print(AA[N//2])
    else:
        print(A[N//2])
else:
    if AA[N//2-1]>A[N//2-1]:
        print(AA[N//2-1])
    else:
        print(A[N//2-1])

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
lis = map(int, raw_input().split())
lis = sorted(lis)
val = ((n*(n+1))/2)
idx = (val/2)+1
summ=0
z=1
for i in xrange(n):
    summ+=(z)
    z+=1
    if summ>=idx:
        print lis[i]
        break

Submission status: Wrong Answer

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

if N%2==1:
    print(A[N//2])
else:
    print(A[N//2-1])

Submission status: Wrong Answer

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

i = int(N/2-1)

print(A[i])

Submission status: Wrong Answer

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

# print(n,k)
m = (n+1)//2
if n%2 == 0:
    print((a[m-1]+a[m])//2)
else:
    print(a[m-1])

Submission status: Wrong Answer

Solution code:
n = int(input())
lis = list(map(int,input().split()))
ans = []
for i in range(n):
  for k in range(n-i):
    li = lis[i:i+k+1]
    li.sort()
  #    print(li,int(len(li)/2))
    ans.append(li[int(len(li)/2)])
print(ans[int(len(ans)/2)])

Submission status: Wrong Answer

Solution code:
import math

N = float(raw_input())
a = sorted(map(int, raw_input().split(' ')))

k = int(math.sqrt((N**2 + N) / 2 + 0.25) + 0.5)
print a[k - 1]

Submission status: Wrong Answer

Solution code:
print(30)

Submission status: Time Limit Exceeded

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

"""
aiが数列mに何回出現するか，がわかれば良い？
左をa個，右をB個見たときに，M=a+B+1として，aiがM//2 +1番目なら良い．
→ai以上の要素が(M+1)//2個以上ある，かつ，此の性質を満たすものの中で最大の数である．
これ辛そう...

でも中央値を求めるのに二分探索は良いよな
結局，答えxの決めうち二分探索で，数列mの中でx以上の要素が何個あるかを知ることができれば解ける．
(x以上のものが(M+1)//2個以上ある中で最大のxを探したい)

つまり，a[l,r]のうち，中央値がx以上になるものはいくつありますか，をときたい
a[l,r]のうちx以上の要素を((r-l+1)+1)/2個以上含むものは何個あるか，がわかれば良いか
x以上ならば+1，そうでなければ-1として，区間の総和が0以上になる区間の個数を探す．
累積和で処理する，S_r-S_(l-1)が0以上ならばOK．このl,rの組を探すのはseg木でできるか，転倒数と同じ要領で．


"""
def main():
    class BIT:
        '''
        0-indexed
        '''
        def __init__(self, N):
            self.size = N
            self.tree = [0] * (N + 1)
            self.depth = N.bit_length()

        def _bitsum(self, i):
            ret = 0
            while i:
                ret += self.tree[i]
                i ^= i & -i
            return ret

        # [l,r)の和
        def sum(self, l, r=None):
            if r is None:
                return self._bitsum(l)
            else:
                return self._bitsum(r) - self._bitsum(l)

        # i番目にxを追加
        def add(self, i, x):
            i += 1
            while i <= self.size:
                self.tree[i] += x
                i += i & -i
            return

        def lower_bound(self, x):
            sum_ = 0
            pos = 0
            v = 1 << self.depth
            for i in range(self.depth, -1, -1):
                k = pos + v
                if k <= self.size and sum_ + self.tree[k] < x:
                    sum_ += self.tree[k]
                    pos += v
                v >>= 1
            return pos + 1, sum_

    N=I()
    A=LI()
    
    
    def calc(x):
        # xを決めたときに，数列mの中でx以上の要素が何個あるか，を返す
        
        B=[0]*N
        for i in range(N):
            if A[i]>=x:
                B[i]=1
            else:
                B[i]=-1
                
        #累積和
        S=[0]*(N+1)
        for i in range(N):
            S[i+1]=S[i]+B[i]
            
        L=[[0,0]for _ in range(N+1)]
        for i in range(N+1):
            L[i]=[S[i],i]
        L.sort()

            
        # Sの値が小さい順に見ていく，そいつの番号を取り出し，そこよりも左側のbitの個数を答えに足していく&そこのbitを立てる
        bit=BIT(N+1)
        res=0
        for i in range(N+1):
            s,ii=L[i]
            temp=bit.sum(0,ii)
            res+=temp
            bit.add(ii,1)
        return res
    
    A2=sorted(A)
    M=(N*N)//2
    ok=0
    ng=N
    
    def ch(x):
        cnt=calc(x)
        # print(x,cnt)
        return cnt>=(M+1)//2

    while ng-ok>1:
        # print(ng,ok)
        med=(ok+ng)//2
        x=A2[med]
        if ch(x):
            ok=med
        else:
            ng=med
        
            
    print(A2[ok])
                
        
    

main()

Submission status: Time Limit Exceeded

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

"""
aiが数列mに何回出現するか，がわかれば良い？
左をa個，右をB個見たときに，M=a+B+1として，aiがM//2 +1番目なら良い．
→ai以上の要素が(M+1)//2個以上ある，かつ，此の性質を満たすものの中で最大の数である．
これ辛そう...

でも中央値を求めるのに二分探索は良いよな
結局，答えxの決めうち二分探索で，数列mの中でx以上の要素が何個あるかを知ることができれば解ける．
(x以上のものが(M+1)//2個以上ある中で最大のxを探したい)

つまり，a[l,r]のうち，中央値がx以上になるものはいくつありますか，をときたい
a[l,r]のうちx以上の要素を((r-l+1)+1)/2個以上含むものは何個あるか，がわかれば良いか
x以上ならば+1，そうでなければ-1として，区間の総和が0以上になる区間の個数を探す．
累積和で処理する，S_r-S_(l-1)が0以上ならばOK．このl,rの組を探すのはseg木でできるか，転倒数と同じ要領で．


"""
def main():
    class BIT:
        '''
        0-indexed
        '''
        def __init__(self, N):
            self.size = N
            self.tree = [0] * (N + 1)
            self.depth = N.bit_length()

        def _bitsum(self, i):
            ret = 0
            while i:
                ret += self.tree[i]
                i ^= i & -i
            return ret

        # [l,r)の和
        def sum(self, l, r=None):
            if r is None:
                return self._bitsum(l)
            else:
                return self._bitsum(r) - self._bitsum(l)

        # i番目にxを追加
        def add(self, i, x):
            i += 1
            while i <= self.size:
                self.tree[i] += x
                i += i & -i
            return

        def lower_bound(self, x):
            sum_ = 0
            pos = 0
            v = 1 << self.depth
            for i in range(self.depth, -1, -1):
                k = pos + v
                if k <= self.size and sum_ + self.tree[k] < x:
                    sum_ += self.tree[k]
                    pos += v
                v >>= 1
            return pos + 1, sum_

    N=I()
    A=LI()
    
    
    def calc(x):
        # xを決めたときに，数列mの中でx以上の要素が何個あるか，を返す
        
        B=[0]*N
        for i in range(N):
            if A[i]>=x:
                B[i]=1
            else:
                B[i]=-1
                
        #累積和
        S=[0]*(N+1)
        for i in range(N):
            S[i+1]=S[i]+B[i]
            
        L=list(range(N+1))
        S,L = zip(*sorted(zip(S, L)))

            
        # Sの値が小さい順に見ていく，そいつの番号を取り出し，そこよりも左側のbitの個数を答えに足していく&そこのbitを立てる
        bit=BIT(N+1)
        res=0
        for i in range(N+1):
            ii=L[i]
            temp=bit.sum(0,ii)
            res+=temp
            bit.add(ii,1)
        return res
    
    A2=sorted(A)
    M=(N*N)//2
    ok=0
    ng=N
    
    def ch(x):
        cnt=calc(x)
        # print(x,cnt)
        return cnt>=(M+1)//2

    while ng-ok>1:
        # print(ng,ok)
        med=(ok+ng)//2
        x=A2[med]
        if ch(x):
            ok=med
        else:
            ng=med
        
            
    print(A2[ok])
                
        
    

main()

Submission status: Time Limit Exceeded

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

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

"""
aiが数列mに何回出現するか，がわかれば良い？
左をa個，右をB個見たときに，M=a+B+1として，aiがM//2 +1番目なら良い．
→ai以上の要素が(M+1)//2個以上ある，かつ，此の性質を満たすものの中で最大の数である．
これ辛そう...

でも中央値を求めるのに二分探索は良いよな
結局，答えxの決めうち二分探索で，数列mの中でx以上の要素が何個あるかを知ることができれば解ける．
(x以上のものが(M+1)//2個以上ある中で最大のxを探したい)

つまり，a[l,r]のうち，中央値がx以上になるものはいくつありますか，をときたい
a[l,r]のうちx以上の要素を((r-l+1)+1)/2個以上含むものは何個あるか，がわかれば良いか
x以上ならば+1，そうでなければ-1として，区間の総和が0以上になる区間の個数を探す．
累積和で処理する，S_r-S_(l-1)が0以上ならばOK．このl,rの組を探すのはseg木でできるか，転倒数と同じ要領で．


"""
def main():
    class BIT:
        '''
        0-indexed
        '''
        def __init__(self, N):
            self.size = N
            self.tree = [0] * (N + 1)
            self.depth = N.bit_length()

        def _bitsum(self, i):
            ret = 0
            while i:
                ret += self.tree[i]
                i ^= i & -i
            return ret

        # [l,r)の和
        def sum(self, l, r=None):
            if r is None:
                return self._bitsum(l)
            else:
                return self._bitsum(r) - self._bitsum(l)

        # i番目にxを追加
        def add(self, i, x):
            i += 1
            while i <= self.size:
                self.tree[i] += x
                i += i & -i
            return

        def lower_bound(self, x):
            sum_ = 0
            pos = 0
            v = 1 << self.depth
            for i in range(self.depth, -1, -1):
                k = pos + v
                if k <= self.size and sum_ + self.tree[k] < x:
                    sum_ += self.tree[k]
                    pos += v
                v >>= 1
            return pos + 1, sum_

    N=I()
    A=LI()
    
    
    def calc(x):
        # xを決めたときに，数列mの中でx以上の要素が何個あるか，を返す
        
        B=[0]*N
        for i in range(N):
            if A[i]>=x:
                B[i]=1
            else:
                B[i]=-1
                
        #累積和
        S=[0]*(N+1)
        for i in range(N):
            S[i+1]=S[i]+B[i]
            
        L=[]
        for i in range(N+1):
            L.append([S[i],i])
        L.sort()
            
        # Sの値が小さい順に見ていく，そいつの番号を取り出し，そこよりも左側のbitの個数を答えに足していく&そこのbitを立てる
        bit=BIT(N+1)
        res=0
        for i in range(N+1):
            s,ii=L[i]
            temp=bit.sum(0,ii)
            res+=temp
            bit.add(ii,1)
        return res
    
    A2=sorted(A)
    M=(N*N)//2
    N2=len(A2)
    ok=0
    ng=N2
    
    def ch(x):
        cnt=calc(x)
        # print(x,cnt)
        return cnt>=(M+1)//2

    while ng-ok>1:
        # print(ng,ok)
        med=(ok+ng)//2
        x=A2[med]
        if ch(x):
            ok=med
        else:
            ng=med
        
            
    print(A2[ok])
                
        
    

main()

Submission status: Time Limit Exceeded

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

mm = []
for i in range(1,N+1):
  for j in range(N-i+1):
    tmp = sorted(a[j:j+i])
    mm.append(tmp[len(tmp)//2])

mm = sorted(mm)
    
print(mm[len(mm)//2])

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate

class BIT:
  def __init__(self, size):
    self.bit = [0] * (size + 1)
    self.size = size

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

  def add(self, i, x):
    i += 1
    while i <= self.size:
      self.bit[i] += x
      i += i & -i

N = int(input())
a = list(map(int, input().split()))
lb, ub = -1, 10**9
while ub - lb > 1:
  m = (lb + ub) // 2
  b = [0] * (N+1)
  for i in range(N):
    if a[i] <= m:
      b[i+1] = 1
  b = list(accumulate(b))
  bit_odd = BIT(2*N)
  bit_even = BIT(2*N)
  cnt = 0
  for i in range(N):
    x = N + b[i+1] - i//2 - 1
    y = N + b[i+1] - (i+1)//2 - 1
    if i % 2 == 0:
      bit_even.add(N + b[i] - i//2, 1)
      cnt += bit_even.sum(x) + bit_odd.sum(y)
    else:
      bit_odd.add(N + b[i] - i//2, 1)
      cnt += bit_even.sum(y) + bit_odd.sum(x)
  if cnt < N*(N+1)//4 + 1:
    lb = m
  else:
    ub = m
print(ub)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
m = (n * (n + 1) // 2) // 2 + 1


class BIT1():
    def __init__(self, n):
        self.n = n
        self.bit = [0] * (self.n + 1)
        self.data = [0] * (self.n + 1)

    def add(self, idx, x):
        # add x to idx-th element
        # idx: 1-indexed
        self.data[idx] += x
        while idx <= self.n:
            self.bit[idx] += x
            idx += (idx & (-idx))

    def sum(self, idx):
        # get sum of [1, idx]
        # idx: 1-indexed
        s = 0
        while idx:
            s += self.bit[idx]
            idx -= (idx & (-idx))
        return s


def check(x):
    # MofM が x以下である
    # x以下の要素が (n*(n+1)//2)//2 + 1 個以上ある

    s = 0
    c = [0] * (n + 1)
    for i in range(n):
        c[i + 1] = c[i]
        if a[i] <= x:
            c[i + 1] += 1
    d = [2 * c[i] - i + n + 1 for i in range(n + 1)]
    d_max = max(d)
    bit = BIT1(d_max)

    cnt = 0
    for i in range(n + 1):
        cnt += bit.sum(d[i] - 1)
        bit.add(d[i], 1)
    return cnt >= m


lb = 0  # False
ub = max(a) + 1  # True
while ub - lb > 1:
    mid = (ub + lb) // 2
    if check(mid):
        ub = mid
    else:
        lb = mid

print(ub)

Submission status: Time Limit Exceeded

Solution code:
def main():
    from itertools import accumulate as ac
    n = int(input())
    a = list(map(int, input().split()))

    class BIT():
        def __init__(self, n):
            self.n = n
            self.bit = [0]*(n+1)

        # 位置iに値vを足す
        def add(self, i, v):
            x = i+1
            while x < self.n + 1:
                self.bit[x] += v
                x += x & (-x)

        # 位置0からiまでの和(sum(bit[:i]))を計算する
        def sum(self, i):
            ret = 0
            x = i
            while x > 0:
                ret += self.bit[x]
                x -= x & (-x)
            return ret

        # 位置iからjまでの和(sum(bit[i:j]))を計算する
        def sum_range(self, i, j):
            return self.sum(j) - self.sum(i)

    if n == 1:
        print(a[0])
        return
    ok = 0
    ng = 10**9+1
    while abs(ok-ng) > 1:
        mid = (ok+ng)//2
        b = [0]+list(ac([(i >= mid)*2-1 for i in a]))
        bit = BIT(2*n+1)
        ans = 0
        bit.add(b[-1]+n, 1)
        for i in range(n-1, -1, -1):
            w = b[i]
            ans += bit.sum_range(w+n, 2*n+1)
            bit.add(w+n, 1)
        if ans >= (n*(n+1)//2)//2:
            ok = mid
        else:
            ng = mid
    print(ok)


main()

Submission status: Time Limit Exceeded

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

from bisect import bisect_left

m = []

for i in range(len(a)):
    sa = sorted(a[i:])
    #m.append(sa[len(sa)//2])
    insi = bisect_left(m, sa[len(sa)//2])
    m.insert(insi, sa[len(sa)//2])
    for j in range(len(a)-1, i, -1):
        deli = bisect_left(sa, a[j])
        del(sa[deli])
        insi = bisect_left(m, sa[len(sa)//2])
        m.insert(insi, sa[len(sa)//2])
        #print(m)
#m.sort()
#print(m)
print(m[len(m)//2])

Submission status: Time Limit Exceeded

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

from bisect import bisect_left

m = []

for i in range(len(a)):
    sa = sorted(a[i:])
    m.append(sa[len(sa)//2])
    for j in range(len(a)-1, i, -1):
        deli = bisect_left(sa, a[j])
        del(sa[deli])
        m.append(sa[len(sa)//2])
m.sort()
print(m[len(m)//2])

Submission status: Time Limit Exceeded

Solution code:
def ABC107D(n, a):
    x = []
    for l in range(n):
        for r in range(l, n):
            m = (r - l + 1) // 2
            b = sorted(a[l:r + 1])
            x.append(b[m])
    y = sorted(x)
    print(y[len(y) // 2])

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def ABC107D(n, a):
    a = np.array(a)
    n = len(a)
    x = []
    for l in range(n):
        for r in range(l, n):
            m = (r - l + 1) // 2
            b = sorted(a[l:r + 1])
            # print(f"l = {l}  r = {r}  m = {m}  a[l:r+1] ={a[l:r+1]}")
            # print(f"b = {b}  b[m] = {b[m]}")
            x.append(b[m])
    y = sorted(x)
    print(y[len(y) // 2])

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

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
try:
    from typing import List
except ImportError:
    pass


class BIT:
    def __init__(self, n: int):
        self.tr = [0] * (n + 1)

    def add(self, n: int, v: int):
        while n < len(self.tr):
            self.tr[n] += v
            n += n & -n

    def cumsum(self, n: int):
        ans = 0
        while n > 0:
            ans += self.tr[n]
            n -= n & -n
        return ans


def solve(N: int, a: "List[int]"):

    def f(m):
        s = [0] * (N + 1)
        for i, ai in enumerate(a):
            s[i + 1] = s[i] + (-1 if ai < m else 1)
        ms = min(s)
        b = BIT(max(s) - ms + 1)
        t = 0
        for si in s:
            t += b.cumsum(si - ms + 1)
            b.add(si - ms + 1, 1)
        return t >= -(-(N * (N + 1) // 2) // 2)

    lb = 0
    rb = max(a) + 1
    while lb + 1 < rb:
        m = (lb + rb) // 2
        if f(m):
            lb = m
        else:
            rb = m

    print(lb)


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    a = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, a)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
class BIT:
    '''
    0-indexed
    '''
    def __init__(self, N):
        self.size = N
        self.tree = [0] * (N + 1)
        self.depth = n.bit_length()
     
    def clear(self):
        self.tree = [0] * (self.size + 1)

    def _bitsum(self, i):
        ret = 0
        while i:
            ret += self.tree[i]
            i ^= i & -i
        return ret

    def bitsum(self, l, r=None): # [l, r)
        if r is None:
            return self._bitsum(l)
        else:
            return self._bitsum(r) - self._bitsum(l)

    def bitadd(self, i, x):
        i += 1
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
        return

n = int(input())
m = (n * (n - 1) // 2) // 2 + 1
a = list(map(int, input().split()))
d = dict()
_a = sorted(set(a))
for i, x in enumerate(_a):
  d[x] = i
a = [d[x] for x in a]
bit = BIT(n+10)

def check(X):
  b = [0] + [(y>=X)*2 - 1 for y in a]
  for i in range(n):
    b[i+1] += b[i]
  c = min(b)
  b = [x-c for x in b] 
  bit.clear()
  ans = 0
  for x in b:
    ans += bit.bitsum(x+1)
    bit.bitadd(x, 1)
  return ans >= m

t = [max(a) + 1, min(a) - 1]
while t[0] - t[1] > 1:
  mid = (t[0] + t[1]) // 2
  t[check(mid)] = mid
print(_a[t[1]])

Submission status: Time Limit Exceeded

Solution code:
class BIT:
    '''
    0-indexed
    '''
    def __init__(self, N):
        self.size = N
        self.tree = [0] * (N + 1)
        self.depth = n.bit_length()
     
    def clear(self):
        self.tree = [0] * (self.size + 1)

    def _bitsum(self, i):
        ret = 0
        while i:
            ret += self.tree[i]
            i ^= i & -i
        return ret

    def bitsum(self, l, r=None): # [l, r)
        if r is None:
            return self._bitsum(l)
        else:
            return self._bitsum(r) - self._bitsum(l)

    def bitadd(self, i, x):
        i += 1
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
        return

n = int(input())
m = (n * (n - 1) // 2) // 2 + 1
a = list(map(int, input().split()))
bit = BIT(n+10)

def check(X):
  b = [0] + [(y>=X)*2 - 1 for y in a]
  for i in range(n):
    b[i+1] += b[i]
  c = min(b)
  b = [x-c for x in b] 
  bit.clear()
  ans = 0
  for x in b:
    ans += bit.bitsum(x+1)
    bit.bitadd(x, 1)
  return ans >= m

t = [max(a) + 1, min(a) - 1]
while t[0] - t[1] > 1:
  mid = (t[0] + t[1]) // 2
  t[check(mid)] = mid
print(t[1])

Submission status: Time Limit Exceeded

Solution code:
class BIT:
    '''
    0-indexed
    '''
    def __init__(self, N):
        self.size = N
        self.tree = [0] * (N + 1)
        self.depth = n.bit_length()

    def _bitsum(self, i):
        ret = 0
        while i:
            ret += self.tree[i]
            i ^= i & -i
        return ret

    def bitsum(self, l, r=None): # [l, r)
        if r is None:
            return self._bitsum(l)
        else:
            return self._bitsum(r) - self._bitsum(l)

    def bitadd(self, i, x):
        i += 1
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
        return

n = int(input())
m = (n * (n - 1) // 2) // 2 + 1
a = list(map(int, input().split()))

def check(X):
  b = [0] + [(y>=X)*2 - 1 for y in a]
  for i in range(n):
    b[i+1] += b[i]
  c = min(b)
  b = [x-c for x in b] 
  bit = BIT(n + 10)
  ans = 0
  for x in b:
    ans += bit.bitsum(x+1)
    bit.bitadd(x, 1)
  return ans >= m

t = [max(a) + 1, min(a) - 1]
while t[0] - t[1] > 1:
  mid = (t[0] + t[1]) // 2
  t[check(mid)] = mid
print(t[1])

Submission status: Time Limit Exceeded

Solution code:
import bisect
import numpy as np
class BinaryIndexedTree():
    def __init__(self,size):
        self.BIT = np.zeros(2*size+1,dtype=int)
    def query(self,index):
        #sum of A1 ~ Ai O(logN)
        ret=0
        while index > 0:
            ret += self.BIT[index]
            index -= index & (-index)
        return ret
    def update(self,index,x):
        #add x to Ai O(logN)
        while index <=  len(self.BIT)-1:
            self.BIT[index] += x
            index += index & (-index)
        return
n=int(input())
a=list(map(int,input().split()))
a2=sorted(a)
if n==1:print(a[0]);exit()
elif n==2:print(a[1]);exit()
ng=2*max(a)+20
ok=0
while ng-ok>1:
    check=(ok+ng)//2
    cnt=0 #check以上の要素の数
    s=np.empty(n+1,int)
    s[0]=0
    B=BinaryIndexedTree(n+1)
    for i in range(1,n+1):
        if a[i-1]<check:s[i]=s[i-1]-1
        else:s[i]=s[i-1]+1

    for i,e in enumerate(s):
        cnt += B.query(e+n+1)
        B.update(e+n+1,1)
    if cnt >= ((n+1)*n)//4:
        ok = check
    else:
        ng = check
print(ok)

Submission status: Time Limit Exceeded

Solution code:
import bisect
import numpy as np
class BinaryIndexedTree():
    def __init__(self,size):
        self.BIT = np.zeros(size+1,dtype=int)
    def query(self,index):
        #sum of A1 ~ Ai O(logN)
        ret=0
        while index > 0:
            ret += self.BIT[index]
            index -= index & (-index)
        return ret
    def update(self,index,x):
        #add x to Ai O(logN)
        while index <=  len(self.BIT)-1:
            self.BIT[index] += x
            index += index & (-index)
        return
n=int(input())
a=list(map(int,input().split()))
if n==1:print(a[0]);exit()
elif n==2:print(a[1]);exit()
ng=2*max(a)+20
ok=0
while ng-ok>1:
    check=(ok+ng)//2
    cnt=0 #check以上の要素の数
    s=np.empty(n+1,int)
    s[0]=0
    B=BinaryIndexedTree(n+1)
    for i in range(1,n+1):
        if a[i-1]<check:s[i]=s[i-1]-1
        else:s[i]=s[i-1]+1
    
    # 座標圧縮
    S=sorted(s)
    for i,e in enumerate(s):
        s[i]=bisect.bisect_left(S,e)
    for i,e in enumerate(s):
        cnt += B.query(e+1)
        B.update(e+1,1)
    if cnt >= ((n+1)*n)//4:
        ok = check
    else:
        ng = check
print(ok)

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys
input = sys.stdin.readline
class BinaryIndexedTree():
    def __init__(self,size):
        self.BIT = [0]*(size+1)
    def query(self,index):
        #sum of A1 ~ Ai O(logN)
        ret=0
        while index > 0:
            ret += self.BIT[index]
            index -= index & (-index)
        return ret
    def update(self,index,x):
        #add x to Ai O(logN)
        while index <=  len(self.BIT)-1:
            self.BIT[index] += x
            index += index & (-index)
        return
n=int(input())
a=list(map(int,input().split()))
if n==1:print(a[0]);exit()
elif n==2:print(a[1]);exit()
ng=2*max(a)+20
ok=0
while ng-ok>1:
    check=(ok+ng)//2
    cnt=0 #check以上の要素の数
    s=[0]*(n+1)
    B=BinaryIndexedTree(n+1)
    for i in range(1,n+1):
        if a[i-1]<check:s[i]=s[i-1]-1
        else:s[i]=s[i-1]+1
    
    # 座標圧縮
    S=sorted(s)
    for i,e in enumerate(s):
        s[i]=bisect.bisect_left(S,e)
    for i,e in enumerate(s):
        cnt += B.query(e+1)
        B.update(e+1,1)
    if cnt >= ((n+1)*n)//4:
        ok = check
    else:
        ng = check
print(ok)

Submission status: Time Limit Exceeded

Solution code:
import bisect
class BinaryIndexedTree():
    def __init__(self,size):
        self.BIT = [0]*(size+1)
    def query(self,index):
        #sum of A1 ~ Ai O(logN)
        ret=0
        while index > 0:
            ret += self.BIT[index]
            index -= index & (-index)
        return ret
    def update(self,index,x):
        #add x to Ai O(logN)
        while index <=  len(self.BIT)-1:
            self.BIT[index] += x
            index += index & (-index)
        return
n=int(input())
a=list(map(int,input().split()))
if n==1:print(a[0]);exit()
elif n==2:print(a[1]);exit()
ng=2*max(a)+20
ok=0
while ng-ok>1:
    check=(ok+ng)//2
    cnt=0 #check以上の要素の数
    s=[0]*(n+1)
    B=BinaryIndexedTree(n+1)
    for i in range(1,n+1):
        if a[i-1]<check:s[i]=s[i-1]-1
        else:s[i]=s[i-1]+1
    
    # 座標圧縮
    S=sorted(s)
    for i,e in enumerate(s):
        s[i]=bisect.bisect_left(S,e)
    for i,e in enumerate(s):
        cnt += B.query(e+1)
        B.update(e+1,1)
    if cnt >= ((n+1)*n)//4:
        ok = check
    else:
        ng = check
print(ok)