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: Accepted

Solution code:
from itertools import accumulate
from math import ceil
N = int(input())
A = list(map(int, input().split()))


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

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

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

    def reset(self):
        self.bit = [0] * (self.size + 1)


# BIT準備
BIT = BinaryIndexedTree(N)
# 答えをにぶたん
lo, hi = -1, max(A) + 1  # sample2などに対応するためにhiを設定
while hi - lo > 1:
    m = (hi + lo) // 2

    # m以上かどうかで分類
    binary = [(1 if a >= m else -1) for a in A]
    binary = list(accumulate(binary))

    # BITの初期化
    BIT.reset()

    # 和が0以上となる連続部分列を数える
    tmp = 0

    # 転倒数っぽくやる
    binary_sorted = {b: i for i, b in enumerate(sorted(binary), start=1)}
    ans = 0
    for j, b in enumerate(binary):
        tmp += BIT.sum(binary_sorted[b]) + (b >= 0)
        BIT.add(binary_sorted[b], 1)

    # 連続する部分列の個数の半分以上和が0以上となる区間が存在するかで場合分け
    if tmp >= ceil(((N * (N + 1)) / 2) / 2):
        lo = m
    else:
        hi = m

print(lo)

Submission status: Accepted

Solution code:
from itertools import accumulate
from math import ceil

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

if N == 1:
    print(A[0])
    exit()


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

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

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

    def reset(self):
        self.bit = [0] * (self.size + 1)


BIT = BinaryIndexedTree(N)  # Binaryの先頭の分
lo, hi = -1, 10 ** 9 + 1
while hi - lo > 1:
    # Xは中央値候補
    X = (hi + lo) // 2

    # X以上なら1、X未満なら-1に変換
    Binary = [(1 if a >= X else -1) for a in A]

    # 累積和をとる
    Binary = list(accumulate(Binary))

    # BITを初期化
    BIT.reset()

    # 転倒数っぽいものを数える
    inversion = 0
    Binary_sorted = {b: i for i, b in enumerate(sorted(Binary), start=1)}
    for j, b in enumerate(Binary):
        inversion += BIT.sum(Binary_sorted[b]) + (b >= 0)
        BIT.add(Binary_sorted[b], 1)

    if inversion >= ceil((N * (N + 1) / 2) / 2):
        lo = X
    else:
        hi = X

print(lo)

Submission status: Accepted

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

def search(x):
    b = n
    r = 0
    y = 0
    D = [0]*(2*n+1)
    for i in range(n):
        D[b] += 1
        if A[i] < x:
            r += D[b]
            b += 1
        else:
            b -= 1
            r -= D[b]   
        y += r
    return y

S = sorted(A)
l = 0
r = n
m = n // 2
c = n * (n + 1) // 2

while True:
    if search(S[m]) <= c // 2:
        if m == n - 1:
            break
        elif search(S[m + 1]) > c // 2:
            break
        else:
            l = m
            m = (m + r) // 2
    else:
        r = m + 1
        m = (m + l) // 2
        
print(S[m])

Submission status: Accepted

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

if n == 1:
    print(a[0])
    exit()

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

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

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

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

    temp = [n for _ in range(n + 1)]
    temp[0] = n + 1
    for i in range(n):
        if a[i] >= b[ans]:
            temp[i + 1] = temp[i] + 1
        else:
            temp[i + 1] = temp[i] - 1
    res = 0
    for i in range(n + 1):
        x = temp[i]
        res += bit_sum(x)
        bit_add(x)
    return res

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

ans = 0

l = 0
r = len(b)
while 1:
    ans = (l + r) // 2
    if count_inversion(ans) * 2 >= m:
        l = ans
    else:
        r = ans
    if r - l <= 1:
        ans = l
        break

print(b[ans])

Submission status: Accepted

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


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

    geta = abs(min(S)) + 1
    for i in range(N + 1):
        S[i] += geta

    forward = 0
    size = max(S)
    bit = [0] * (size + 1)
    for s in S:
        i = s
        while i > 0:
            forward += bit[i]
            i -= i & -i

        i = s
        while i <= size:
            bit[i] += 1
            i += i & -i

    return forward >= (M + 1) // 2


M = N * (N + 1) // 2  # (N+1)C2
sorted_A = sorted(A)

inf = 0
sup = N
while sup - inf > 1:
    mid = (sup + inf) // 2
    x = sorted_A[mid]

    if sub_problem(x):
        inf = mid
    else:
        sup = mid

print(sorted_A[inf])

Submission status: Accepted

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

class BIT:
    # index 1~
    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 sub_problem(x):
    S = [0] * (N + 1)
    for i in range(N):
        S[i + 1] = S[i] + 1 if A[i] >= x else S[i] - 1

    geta = abs(min(S)) + 1
    for i in range(N + 1):
        S[i] += geta

    forward = 0
    bit = BIT(max(S))
    for s in S:
        forward += bit.sum(s)
        bit.add(s, 1)

    return forward >= M // 2 # TEST　これだと通らないはず

M = N * (N + 1) // 2  # (N+1)C2
sorted_A = sorted(A)

inf = 0
sup = N
while sup - inf > 1:
    mid = (sup + inf) // 2
    x = sorted_A[mid]

    if sub_problem(x):
        inf = mid
    else:
        sup = mid

print(sorted_A[inf])

Submission status: Accepted

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

class BIT:
    # index 1~
    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 sub_problem(x):
    S = [0] * (N + 1)
    for i in range(N):
        S[i + 1] = S[i] + 1 if A[i] >= x else S[i] - 1

    geta = abs(min(S)) + 1
    for i in range(N + 1):
        S[i] += geta

    forward = 0
    bit = BIT(max(S))
    for s in S:
        forward += bit.sum(s)
        bit.add(s, 1)

    return forward >= (M + 1) // 2

M = N * (N + 1) // 2  # (N+1)C2
sorted_A = sorted(A)

inf = 0
sup = N
while sup - inf > 1:
    mid = (sup + inf) // 2
    x = sorted_A[mid]

    if sub_problem(x):
        inf = mid
    else:
        sup = mid

print(sorted_A[inf])

Submission status: Accepted

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


class BIT:
    # index 1~
    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


M = N * (N + 1) // 2  # (N+1)C2
sorted_A = sorted(A)

inf = 0
sup = max(A) + 1
while sup - inf > 1:
    x = (sup + inf) // 2

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

    min_value = min(S)
    for i in range(N + 1):
        S[i] += abs(min_value) + 1

    forward = 0
    bit = BIT(max(S))
    for s in S:
        forward += bit.sum(s)
        bit.add(s, 1)

    if forward >= (M + 1) // 2:
        inf = x
    else:
        sup = x

for a in reversed(sorted_A):
    if inf >= a:
        print(a)
        break

Submission status: Accepted

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
          
            bitobje+=(bitobje &(-bitobje))

    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: Accepted

Solution code:
#!/usr/bin/env pypy3
# -*- 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):
    global T

    if t - f <= 1:
        return 0

    mid = (f + t) // 2
    n1 = mergesort(S, f, mid)
    n2 = mergesort(S, mid, t)
    n = n1 + n2
    i = f
    j = mid
    k = f
    while i < mid and j < t:
        if S[i] <= S[j]:
            T[k] = S[i]
            i += 1
            n += t - j
        else:
            T[k] = S[j]
            j += 1
        k += 1

    while i < mid:
        T[k] = S[i]
        i += 1
        k += 1
    assert k == j
    for i in range(f, k):
        S[i] = T[i]
    return n

def inversion(S):
    """リストSの転倒数"""
    global T
    T = [0] * len(S)
    return mergesort(S, 0, len(S))

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: Accepted

Solution code:
N = int(input())
a_list = list(map(int, input().split()))
def search(c):
    bar = N
    r = 0
    res_nega = 0
    dp_arr = [0]*(2*N+1)
    for i in range(N):
        dp_arr[bar] += 1
        if a_list[i] < c:
            r += dp_arr[bar]
            bar += 1
        else:
            r -= (dp_arr[bar-1])
            bar -= 1
        res_nega += r
    return res_nega
# binary search
a_sorted = sorted(a_list)
left = 0
right = N
mid = N // 2
C = N*(N+1) // 2
while True:
    if search(a_sorted[mid]) <= C // 2:
        if mid == N-1:
            break
        elif search(a_sorted[mid+1]) > C // 2:
            break
        else:
            left = mid
            mid = (mid + right) // 2
    else:
        right = mid + 1
        mid = (mid + left) // 2
print(a_sorted[mid])

Submission status: Accepted

Solution code:
N = int(input())
a = [int(x) for x in input().split()]

b = sorted(a)
M = ((N + 1) * N // 2 + 1) // 2


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

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

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


def is_OK(x):
    S = [1] * N
    for i in range(N):
        if a[i] < x:
            S[i] = -1
        if i > 0:
            S[i] += S[i - 1]
    S = [0] + S
    min_S = min(S)
    max_S = max(S)

    bit = BIT(max_S - min_S + 1)
    cnt = 0
    for S_i in S:
        S_i = S_i - min_S + 1
        cnt += bit.sum(S_i)
        bit.add(S_i, 1)
    return cnt >= M


left, right = 0, 10 ** 9 + 1
while right - left > 1:
    mid = (left + right) // 2
    if is_OK(mid):
        left = mid
    else:
        right = mid

print(left)

Submission status: Accepted

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

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
    c = 0; d = 10**18
    for a in A:
        if x <= a:
            c += 1
        else:
            c -= 1
        d = min(c, d)
    res = N*(N+1)//2
    c = -d+1
    for a in A:
        res -= get(c)
        if x <= a:
            c += 1
        else:
            c -= 1
        add(c, 1)
    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)

Submission status: Runtime Error

Solution code:
from math import ceil
from itertools import accumulate
n = int(input())
import math
import numpy as np
import decimal
import collections
import itertools
import sys
#Union-Find
def find(x):
    if par[x] < 0:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
def unite(x, y):
    p = find(x)
    q = find(y)
    if p == q:
        return None
    if p > q:
        p,q = q,p
    par[p] += par[q]
    par[q] = p
def same(x, y):
    return find(x) == find(y)
def size(x):
    return -par[find(x)]
par = [-1 for i in range(n)]

#素数関連
def prime_numbers(x):
    if x < 2:
        return []
    prime_numbers = [i for i in range(x)]
    prime_numbers[1] = 0
    for prime_number in prime_numbers:
        if prime_number > math.sqrt(x):
            break
        if prime_number == 0:
            continue
        for composite_number in range(2 * prime_number, x, prime_number):
            prime_numbers[composite_number] = 0
    return [prime_number for prime_number in prime_numbers if prime_number != 0]
def is_prime(x):
    if x < 2:
        return False
    if x == 2 or x == 3 or x == 5:
        return True
    if x % 2 == 0 or x % 3 == 0 or x % 5 == 0:
        return False
    prime_number = 7
    difference = 4
    while prime_number <= math.sqrt(x):
        if x % prime_number == 0:
            return False
        prime_number += difference
        difference = 6 - difference
    return True
#nCr
mod = 10 ** 9 + 7
def comb(n, r):
    if n < r:return 0
    if n < 0 or r < 0:return 0
    return fa[n] * fi[r] % mod * fi[n - r] % mod
fa = [1] * (n + 1)
fi = [1] * (n + 1)
for i in range(1, n + 1):
    fa[i] = fa[i - 1] * i % mod
    fi[i] = pow(fa[i], mod - 2, mod)
def add(i, x):
    while i <= len(BIT):
        BIT[i] += x
        i += i & -i
def query(i):
    s = 0
    while i > 0:
        s += BIT[i]
        i -= i & -i
    return s
a = list(map(int, input().split()))
lis = sorted(list(set(a)))
l, r = 0, len(lis)
while r - l > 1:
    BIT = [0] * (2 * (n + 1) + 100)
    m = (l + r) // 2
    cum = [0]
    for i in range(n):
        cur = 1 if a[i] >= lis[m] else -1
        cum.append(cum[-1] + cur)
    cnt = 0
    for i in range(n + 1):
        cur = n + cum[i] + 5
        cnt += query(cur)
        add(cur, 1)
    if n * (n + 1) // 2 <= cnt * 2:
        l = m 
    else:
        r = m
print(lis[l])

Submission status: Runtime Error

Solution code:

def f(n, a):
    x = sorted(set(a))
    n_sub_half = (n * (n + 1)) // 2 // 2
    n1 = n * 2 + 1
    li = 0
    ri = len(x)
    while ri > li + 1:
        i = (li + ri) // 2
        xi = x[i]
        cnt = [0] * n1
        cs = 0
        cnt[cs] = 1
        judge = 0
        s = 0
        for ak in a:
            if ak >= xi:
                cs += 1
                s += cnt[cs] + 1
            else:
                cs -= 1
                s -= cnt[cs + 1] - 1
            cnt[cs] += 1
            judge += s
            if judge >= n_sub_half:
                li = i
                break
        else:
            ri = i
    return x[ri]

n = int(input())
ar = [int(i) for i in input().strip().split(" ")]
print(f(n,ar))

Submission status: Runtime Error

Solution code:
from collections import defaultdict

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

scores = defaultdict(int)

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

for i in range(N//2):
  scores[a[i]] += 2*(i+1)
  scores[a[-i-1]] += 2*(i+1)

if N%2==1:
  scores[a[N//2+1]] += 2*(N//2+1)

for i in range(len(b)//2):
  scores[b[i]] += 2*(i+1)
  scores[b[-i-1]] += 2*(i+1)

if len(b)%2==1:
  scores[b[len(b)//2+1]] += 2*(len(b)//2+1)

MAX=0
argmax=-1
for i in range(N):
  if scores[a[i]] > MAX:
    MAX=scores[a[i]]
    argmax=a[i]

print(argmax)

Submission status: Runtime Error

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

scores = [0]*(10**5+5)

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

for i in range(N//2):
  scores[a[i]] += 2*(i+1)
  scores[a[-i-1]] += 2*(i+1)

if N%2==1:
  scores[a[N//2+1]] += 2*(N//2+1)

for i in range(len(b)//2):
  scores[b[i]] += 2*(i+1)
  scores[b[-i-1]] += 2*(i+1)

if len(b)%2==1:
  scores[b[len(b)//2+1]] += 2*(len(b)//2+1)

MAX=0
argmax=-1
for i in range(len(scores)):
  if scores[i] > MAX:
    MAX=scores[i]
    argmax=i

print(argmax)

Submission status: Runtime Error

Solution code:
N=int(input())
a=list(map(int,input().split()))
A=sorted(set(a))
M=len(A)

if N==1:
    print(a[0])
    exit()
elif N==2:
    print(a[1])
    exit()

def count(sequence):
    cnt=0
    for i in range(len(sequence)-1):
        for j in range(i+1,len(sequence)):
            if sequence[i]<=sequence[j]:
                cnt+=1
    return cnt


low=0
high=M
while high-low>1:
    mid=(high+low)//2
    check=A[mid]
    cnt=0
    S=[0]*(N)
    if a[0]>=check:
        S[0]=1
    else:
        S[0]=-1
    for i in range(1,N):
        if a[i]>=check:
            S[i]=S[i-1]+1
        else:
            S[i]=S[i-1]-1
    n=count(S)
    if n>=((N+1)*N//2)//2:
        low=mid
    else:
        high=mid
print(A[mid])

Submission status: Runtime Error

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
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]


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 = [len(_a) + 1, -1]
while t[0] - t[1] > 1:
  mid = (t[0] + t[1]) // 2
  t[check(mid)] = mid
print(_a[t[1]])

Submission status: Runtime Error

Solution code:
class BIT_RSQ():
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)

    def add(self, i, v):
        while i <= self.n:
            self.data[i-1] += v
            i += i & -i

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

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

def check(m):
    b = [[-1,1][i>=m] for i in a]
    bit = BIT_RSQ(2*n+1)
    s = [0] + list(accumulate(b))
    res = 0
    for i in range(n):
        bit.add(s[i]+n+1, 1)
        res += bit.sum(s[i+1]+n+1)
    return res >= (n*(n+1)//2+1)//2

left = 0
right = 10**9+1
while right-left > 1:
    mid = (right+left)//2
    if check(mid):
        left = mid
    else:
        right = mid
print(left)

Submission status: Runtime Error

Solution code:
import math
from statistics import median_high as med

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

medians = []
for i in range(N + 1):
    for j in range(i+1, N + 1):
        print(A[i:j])
        medians.append(med(A[i:j]))

print(med(medians))

Submission status: Runtime Error

Solution code:
n = int(input())
a = [int(i) for i in input().split()]
t = []
for i in range(n - 1):
    for j in range(i + 1, n):
        if (j - i) % 2 == 0:
            t.append(sorted(a[i:j+1])[((j-i)//2)])
        else:
            t.append(sorted(a[i:j+1])[((j-i)//2)+1])
len_t = len(t)
if len_t % 2 == 0:
    print(t[len_t // 2])
else:
    print(t[(len_t // 2) + 1])

Submission status: Runtime Error

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


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 f(x):  # 連続部分列の中央値がｘなる場合の数
    s = Bit(2)
    S = Bit(2 * n + 1)
    judge = 0
    for p in a:
        s.add((p >= x) + 1, 1)
        b = n + s.tree[2] - 2 * s.tree[1]
        S.add(b,1)
        judge += S.sum(b)
        if judge >= n_sub_half:
            return 1
    return 0


b = sorted(set(a))
l, r = 0, len(b)
n_sub_half = (n * (n + 1) // 2) // 2
while True:
    m = (r + l + 1) // 2
    if f(b[m]):  # ans >= x
        if m == len(b) - 1:
            break
        elif not f(b[m + 1]):
            break
        else:
            l = m
    else:  # ans < x
        r = m - 1


print(b[m])

Submission status: Runtime Error

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


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 f(x):  # 連続部分列の中央値がｘなる場合の数
    s = Bit(2)
    S = Bit(2 * n + 1)
    judge = 0
    for p in a:
        s.add((p >= x) + 1, 1)
        b = n + s.tree[2] - 2 * s.tree[1]
        S.add(b,1)
        judge += S.sum(b)
        if judge >= n_sub_half:
            return 1
    return 0


b = sorted(set(a))
l, r = 0, len(b)
n_sub_half = (n * (n + 1) // 2) // 2
while True:
    m = (r + l) // 2 + 1
    if f(b[m]):  # ans >= x
        if m == len(b) - 1:
            break
        elif not f(b[m + 1]):
            break
        else:
            l = m + 1
    else:  # ans < x
        r = m - 1


print(b[m])

Submission status: Runtime Error

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


def f(x):
    bit = [0] * 2
    BIT = [0] * (2 * n + 1)
    judge = 0
    for p in a:
        if p >= x:
            bit[1] += 1
        else:
            bit[0] -= 1
        i = sum(bit) + n + 1
        r = 0
        while i <= 2 * n + 1:
            BIT[i] += 1
            i += i & - i
        i = sum(bit) + n + 1
        while i > 0:
            r += BIT[i]
            i -= i & - i
        judge += r
        if judge >= n_sub_half:
            return 1
    return 0

b = sorted(set(a))
l, r = 0, len(b)
n_sub_half = (n * (n + 1) // 2) // 2
while True:
    m = (r + l) // 2
    if f(b[m]):
        if m == len(b) - 1:
            break
        elif not f(b[m + 1]):
            break
        else:
            l = m
    else:
        r = m - 1


print(b[m])

Submission status: Runtime Error

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


def f(x):
    bit = [0] * 2
    BIT = [0] * (2 * n + 1)
    judge = 0
    for p in a: #[1,4,3]=>[-1,1,1] if ai >= x bi = 1 else -1
        if p >= x:
            bit[1] += 1
        else:
            bit[0] -= 1
        i = sum(bit) + n + 1
        r = 0
        while i <= 2 * n + 1: #biの更新
            BIT[i] += 1
            i += i & - i
        i = sum(bit) + n + 1
        while i > 0:
            r += BIT[i]
            i -= i & - i
        judge += r
        if judge >= n_sub_half:
            return 1
    return 0

b = sorted(set(a))
l, r = 0, len(b)
n_sub_half = (n * (n + 1) // 2) // 2
while True:
    m = (r + l) // 2
    if f(b[m]):
        if m == len(b) - 1:
            break
        elif not f(b[m + 1]):
            break
        else:
            l = m
    else:
        r = m - 1


print(b[m])

Submission status: Runtime Error

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


def f(x):
    bit = [0] * 2
    BIT = [0] * (2 * n + 1)
    judge = 0
    for p in a: #[1,4,3]=>[-1,1,1] if ai >= x bi = 1 else -1
        if p >= x:
            bit[1] += 1
        else:
            bit[0] -= 1
        i = sum(bit) + n + 1
        r = 0
        while i <= 2 * n + 1: #biの更新
            BIT[i] += 1
            i += i & - i
        i = sum(bit) + n + 1
        while i > 0:
            r += BIT[i]
            i -= i & - i
        judge += r
        if judge >= n_sub_half:
            print(BIT,bit,x)
            return 1
    return 0

b = sorted(set(a))
l, r = 0, len(b)
n_sub_half = (n * (n + 1) // 2) // 2
while True:
    m = (r + l) // 2
    if f(b[m]):
        if m == len(b) - 1:
            break
        elif not f(b[m + 1]):
            break
        else:
            l = m
    else:
        r = m - 1


print(b[m])

Submission status: Runtime Error

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


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

    def sum(self, i):
        s = 0
        while self.size >= 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 f(x):  # 連続部分列の中央値がｘなる場合の数
    s = Bit(2)
    S = []
    for p in a:
        s.add((p >= x) + 1, 1)
        S.append(s.tree[2] - 2 * s.tree[1])
    t3 = time.time()
    ret = 0
    bit = Bit(n)
    w = abs(min(S)) + 1
    for p in S:
        bit.add(p + w, 1)
        ret += bit.sum(p + w)
    t4 = time.time()
    return ret


b = sorted(set(a))
l, r = 0, len(b)
n_sub_half = (n * (n + 1) // 2) // 2
while True:
    m = (r + l) // 2
    if f(b[m]) >= n_sub_half:  # ans >= x
        if m == len(b) - 1:
            break
        elif f(b[m + 1]) < n_sub_half:
            break
        else:
            l = m
    else:  # ans < x
        r = m - 1


print(b[m])

Submission status: Runtime Error

Solution code:
N = int(input())
A = [int(x) for x in input().split()]
total_medians = N*(N+1)//2
# n件のデータ
# (上側中央値 >= x) iff (a > x となる a が(n-1)//2以下)

def test(x):
  # 「答はx以下である」
  # 「xより真に大きな区間中央値が(total_medians-1)//2個以下」
  B = [0]
  for a in A:
    B.append(B[-1] + (1 if a > x else -1))
  m = min(B)-1
  BIT = [0]*(N+1)
  cnt = 0
  for b in B:
    x = b-m
    while x:
      cnt += BIT[x]
      x -= (x & (-x))
    x = b-m
    b -= m
    while x <= N:
      BIT[x] += 1
      x += (x & (-x))
  return cnt <= (total_medians-1)//2

AA = sorted(A)
left = -1 # 答はAA[left]より大きい
right = len(AA)-1 # 答はAA[right]以下である
while right - left > 1:
  mid = (left+right)//2
  if test(AA[mid]):
    right = mid
  else:
    left = mid
    
answer = AA[right]
print(answer)

Submission status: Runtime Error

Solution code:
import numpy as np
N = int(input())
A = np.array(input().split(),dtype=np.int32)
total_medians = N*(N+1)//2
# n件のデータ
# (上側中央値 >= x) iff (a > x となる a が(n-1)//2以下)

def BIT_update(BIT,x,value):
  # 番号xにvalueを加える
  L = len(BIT)
  while x < L:
    BIT[x] += value
    bottom_bit = x & (-x)
    x += bottom_bit
  return

def BIT_sum(BIT,x):
  # 番号1～xの和を求める
  result = 0
  while x:
    result += BIT[x]
    bottom_bit = x & (-x)
    x -= bottom_bit
  return result

def test(x):
  # 「答はx以下である」
  # 「xより真に大きな区間中央値が(total_medians-1)//2個以下」
  B = np.concatenate([[0],(A > x).cumsum()])
  # count L,R such that -1<=L<R<=N-1 and B(R)-B(L) >= (R-L)/2
  # count L,R such that B(R) - R/2 >= B(L) - L/2
  C = 2*B-np.arange(N+1)
  C -= np.min(C) - 1
  M = C.max()
  BIT = [0]*(M+1)
  
  cnt = 0
  prev = C[0]
  for c in C[1:]:
    BIT_update(BIT,prev,1)
    cnt += BIT_sum(BIT,c) # 右端がRとなる(L,R)対
    prev = c
  return cnt <= (total_medians-1)//2

AA = sorted(set(A))
left = -1 # 答はAA[left]より大きい
right = len(AA)-1 # 答はAA[right]以下である
while right - left > 1:
  mid = (left+right)//2
  if test(AA[mid]):
    right = mid
  else:
    left = mid
    
answer = AA[right]
print(answer)