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:
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(list(set(A)))
    M=(N*(N-1))//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: Wrong Answer

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_

    mod=10**9+7
    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-1))//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: Wrong Answer

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 Segtree:
        def __init__(self, A, ide_ele, initialize = True, segf = max):
            self.N = len(A)
            self.N0 = 2**(self.N-1).bit_length()
            self.ide_ele = ide_ele
            self.segf = segf
            if initialize:
                self.data = [ide_ele]*self.N0 + A + [ide_ele]*(self.N0 - self.N)
                for i in range(self.N0-1, 0, -1):
                    self.data[i] = self.segf(self.data[2*i], self.data[2*i+1]) 
            else:
                self.data = [ide_ele]*(2*self.N0)

        def update(self, k, x):
            k += self.N0
            self.data[k] = x
            while k > 0 :
                k = k >> 1
                self.data[k] = self.segf(self.data[2*k], self.data[2*k+1])

        def query(self, l, r):
            L, R = l+self.N0, r+self.N0
            s = self.ide_ele
            t = self.ide_ele
            while L < R:
                if L & 1:
                    s = self.segf(s,self.data[L])
                    L += 1
                if R & 1:
                    R -= 1
                    t = self.segf(self.data[R],t)
                L >>= 1
                R >>= 1
            return self.segf(s,t)

        # セグ木上で二分探索，[l,r)の範囲でcheck関数を満たす最小の値をとるところのindexを返す．
        # reverse=Trueなら最大値かな
        # ない時の返り値がNoneなことに注意
        def Binsearch(self, l, r, check, reverse = False):
            L, R = l+self.N0, r+self.N0
            SL, SR = [], []
            while L < R:
                if R & 1:
                    R -= 1
                    SR.append(R)
                if L & 1:
                    SL.append(L)
                    L += 1
                L >>= 1
                R >>= 1

            if reverse:
                pre = self.ide_ele
                for idx in (SR + SL[::-1]):
                    if check(self.segf(self.data[idx], pre)):
                        Break
                    else:
                        pre = self.segf(self.data[idx], pre)
                else:
                    return None
                while idx < self.N0:
                    if check(self.segf(self.data[2*idx+1], pre)):
                        idx = 2*idx + 1
                    else:
                        pre = self.segf(self.data[2*idx+1], pre)
                        idx = 2*idx
                return idx - self.N0
            else:
                pre = self.ide_ele
                for idx in (SL + SR[::-1]):
                    if not check(self.segf(pre, self.data[idx])):
                        pre = self.segf(pre, self.data[idx])
                    else:
                        Break
                else:
                    return None
                while idx < self.N0:
                    if check(self.segf(pre, self.data[2*idx])):
                        idx = 2*idx
                    else:
                        pre = self.segf(pre, self.data[2*idx])
                        idx = 2*idx + 1
                return idx - self.N0
    mod=10**9+7
    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を立てる
        seg=Segtree([0]*(N+1),0,segf=lambda a,b:a+b)
        res=0
        for i in range(N+1):
            s,ii=L[i]
            temp=seg.query(0,ii)
            res+=temp
            seg.update(ii,1)
        return res
    
    A2=sorted(A)
    M=(N*(N-1))//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: Wrong Answer

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 Segtree:
        def __init__(self, A, ide_ele, initialize = True, segf = max):
            self.N = len(A)
            self.N0 = 2**(self.N-1).bit_length()
            self.ide_ele = ide_ele
            self.segf = segf
            if initialize:
                self.data = [ide_ele]*self.N0 + A + [ide_ele]*(self.N0 - self.N)
                for i in range(self.N0-1, 0, -1):
                    self.data[i] = self.segf(self.data[2*i], self.data[2*i+1]) 
            else:
                self.data = [ide_ele]*(2*self.N0)

        def update(self, k, x):
            k += self.N0
            self.data[k] = x
            while k > 0 :
                k = k >> 1
                self.data[k] = self.segf(self.data[2*k], self.data[2*k+1])

        def query(self, l, r):
            L, R = l+self.N0, r+self.N0
            s = self.ide_ele
            t = self.ide_ele
            while L < R:
                if L & 1:
                    s = self.segf(s,self.data[L])
                    L += 1
                if R & 1:
                    R -= 1
                    t = self.segf(self.data[R],t)
                L >>= 1
                R >>= 1
            return self.segf(s,t)

        # セグ木上で二分探索，[l,r)の範囲でcheck関数を満たす最小の値をとるところのindexを返す．
        # reverse=Trueなら最大値かな
        # ない時の返り値がNoneなことに注意
        def Binsearch(self, l, r, check, reverse = False):
            L, R = l+self.N0, r+self.N0
            SL, SR = [], []
            while L < R:
                if R & 1:
                    R -= 1
                    SR.append(R)
                if L & 1:
                    SL.append(L)
                    L += 1
                L >>= 1
                R >>= 1

            if reverse:
                pre = self.ide_ele
                for idx in (SR + SL[::-1]):
                    if check(self.segf(self.data[idx], pre)):
                        Break
                    else:
                        pre = self.segf(self.data[idx], pre)
                else:
                    return None
                while idx < self.N0:
                    if check(self.segf(self.data[2*idx+1], pre)):
                        idx = 2*idx + 1
                    else:
                        pre = self.segf(self.data[2*idx+1], pre)
                        idx = 2*idx
                return idx - self.N0
            else:
                pre = self.ide_ele
                for idx in (SL + SR[::-1]):
                    if not check(self.segf(pre, self.data[idx])):
                        pre = self.segf(pre, self.data[idx])
                    else:
                        Break
                else:
                    return None
                while idx < self.N0:
                    if check(self.segf(pre, self.data[2*idx])):
                        idx = 2*idx
                    else:
                        pre = self.segf(pre, self.data[2*idx])
                        idx = 2*idx + 1
                return idx - self.N0
    mod=10**9+7
    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を立てる
        seg=Segtree([0]*(N+1),0,segf=lambda a,b:a+b)
        res=0
        for i in range(N+1):
            s,ii=L[i]
            temp=seg.query(0,ii)
            res+=temp
            seg.update(ii,1)
        return res
    
    A2=sorted(A)
    M=(N*(N-1))//2
    ok=0
    ng=N
    
    def ch(x):
        cnt=calc(x)
        # print(x,cnt)
        return cnt>=(M+1)//2
    
    aaaaa=0
    while ng-ok>1:
        # print(ng,ok)
        med=(ok+ng)//2
        x=A2[med]
        if ch(x):
            ok=med
        else:
            ng=med
            
        aaaaa+=1
        if aaaaa>=100:
            break
            
    print(A2[ok])
                
        
    

main()

Submission status: Wrong Answer

Solution code:
from math import ceil
from itertools import accumulate
n = int(input())
def add(i, x):
    while i <= n:
        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()))
l, r = 0, max(a)
while r - l > 1:
    BIT = [0] * (n + 1)
    m = (l + r) // 2
    lis = []
    ten = 0
    for i in range(n):
        if a[i] >= m:
            lis.append(1)
        else:
            lis.append(-1)
    lis = list(accumulate(lis))
    lis = list(map(lambda x:x - min(lis) + 1, lis))
    for i in range(n):
        ten += i - query(lis[i])
        add(lis[i], 1)
    if ten > ceil(m / 2):
        r = m
    else:
        l = m
print(r)

Submission status: Wrong Answer

Solution code:
def examA():
    N, i = LI()
    ans = N - i + 1
    print(ans)
    return

def examB():
    H, W = LI()
    A = [SI() for _ in range(H)]
    h = [[]for _ in range(H)]
    for i in range(W):
        flag = False
        for j in range(H):
            if A[j][i]=="#":
                flag = True
                break
        if flag:
            for j in range(H):
                h[j].append(A[j][i])
    #print(h)
    ans = []
    for i,a in enumerate(h):
        if "#" in a:
            ans.append(i)
    for v in ans:
        print("".join(map(str,h[v])))
    return

def examC():
    N, K = LI()
    X = LI()
    ans = inf
    for i in range(N-K+1):
        if X[i]<0 and X[i+K-1]>0:
            cur = (-X[i] + X[i+K-1]) + min(-X[i], X[i+K-1])
        else:
            cur = max(-X[i], X[i+K-1])
        ans = min(ans,cur)
    print(ans)
    return

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

        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
            return
    def inversion_number(n,A):
        bit = Bit(n+1)
        rep = 0
        for i, a in enumerate(A):
            bit.add(a, 1)
            rep += i + 1 - bit.sum(a)
        return rep
    N = I()
    A = LI()
    judge = (N*(N+1)//2)//2
    l = 0; r = max(A)+1
    while(r-l>1):
        #print(l,r)
        now = (l+r)//2
        S = [0]*N
        cur = N*(N+1)//2
        for i in range(N):
            if A[i]>=now:
                S[i] += 1
            else:
                S[i] -= 1
                cur -= 1
        for i in range(N-1):
            S[i+1] += S[i]
            S[i] += N
        S[-1] += N
        #print(S)
        cur -= inversion_number(2*N+10,S)
        #print(judge,cur,S,now)
        #print(cur,now)
        #input()
        if cur>=judge:
            l = now
        else:
            r = now

    ans = l
    print(ans)
    return

import sys,copy,bisect,itertools,heapq,math,random
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examD()

"""

"""

Submission status: Wrong Answer

Solution code:
n = int(raw_input())
ais = map(int, raw_input().split())
ais.sort()


q =  n * (n+1)/2

def f(index, ais):

	q= index - 1
	for i in range(len(ais)):
		q = max(0, q - (i+1))
		if q == 0:
			break
	return ais[i]
if q % 2:	 	
	print f(q/2, ais)
else:
	print (f(q/2, ais) + f(q/2 + 1, ais))/2.0

Submission status: Wrong Answer

Solution code:
from itertools import accumulate
import sys
input = sys.stdin.readline

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))
    # b[j+1] - b[i] > (j - i) // 2 + 1
    # b[j+1] - b[i] > (j+1)//2 - i//2
    # b[j+1] - (j+1)//2 > b[i] - i//2
    bit = BIT(2*N)
    cnt = 0
    for i in range(N):
        bit.add(N + b[i] - i//2, 1)
        x = N + b[i+1] - (i+1)//2 - 1
        if x >= 0:
            cnt += bit.sum(x)
    if cnt < N*(N+1)//4 + 1:
        lb = m
    else:
        ub = m
print(ub)

Submission status: Wrong Answer

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

class BIT():
    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
ok = 0
ng = 10**9+1

def inversion(a, bit):
    ans = 0
    for i, p in enumerate(b):
        bit.add(p, 1)
        ans += i+1 - bit.sum(p)
    return ans

while ng - ok > 1:
    m = ok + (ng-ok)//2
    b = [0]
    for i in range(n):
        if a[i] >= m:
            b.append(b[i]+1)
        else:
            b.append(b[i]-1)
    b = [i+100001 for i in b]
    bit = BIT(200005)
    inversion = 0
    for i, p in enumerate(b):
        bit.add(p, 1)
        inversion += i+1 - bit.sum(p)

    if inversion <= n*(n+1)//4:
        ok = m
    else:
        ng = m

    print(m)


print(ok)

Submission status: Wrong Answer

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

class BIT():
    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
ok = 0
ng = 10**9+1

def inversion(a, bit):
    ans = 0
    for i, p in enumerate(b):
        bit.add(p, 1)
        ans += i+1 - bit.sum(p)
    return ans

while ng - ok > 1:
    m = ok + (ng-ok)//2
    b = [0]
    for i in range(n):
        if a[i] >= m:
            b.append(b[i]+1)
        else:
            b.append(b[i]-1)
    b = [i+100001 for i in b]
    bit = BIT(200005)
    inversion = 0
    for i, p in enumerate(b):
        bit.add(p, 1)
        inversion += bit.sum(p) - 1

    if inversion >= n*(n+1)//4+1:
        ok = m
    else:
        ng = m


print(ok)

Submission status: Wrong Answer

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

class BIT():
    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
ok = 0
ng = 10**9+1

def inversion(a, bit):
    ans = 0
    for i, p in enumerate(b):
        bit.add(p, 1)
        ans += i+1 - bit.sum(p)
    return ans

while ng - ok > 1:
    m = ok + (ng-ok)//2
    b = [0]
    for i in range(n):
        if a[i] >= m:
            b.append(b[i]+1)
        else:
            b.append(b[i]-1)
    b = [i+100001 for i in b]
    bit = BIT(200005)
    inversion = 0
    for i, p in enumerate(b):
        bit.add(p, 1)
        inversion += i+1 - bit.sum(p)

    if inversion < n**2//2+1:
        ok = m
    else:
        ng = m


print(ok)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)
def input(): return sys.stdin.readline().strip()


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

    """
    決め打ち二分探索な匂いがする。
    ans <= Xとするとこれはmedian[l, r] <= Xなるものが(N * (N + 1) // 2) // 2 + 1個以上存在することに同値。
    median[l, r] <= Xなるものの個数は以下の用にして求まる
    １、所与の数列の各元に対して、それがX未満なら-1、X以上なら+1に置き換える
    ２、その数列の累積和をとり、先頭に0を追加。
    ３、この数列の転倒数(i < j s.t.A[i] > A[j])を数えると、その個数がmedian[l, r] <= Xなるものの個数
    """

    left = 0
    right = 10 ** 9
    while right - left > 1:
        #print("left={}, right={}".format(left, right))
        mid = (left + right) // 2
        B = [0] * (N + 1)
        for i in range(1, N + 1):
            if A[i - 1] < mid: B[i] = B[i - 1] - 1
            if A[i - 1] >= mid: B[i] = B[i - 1] + 1
        #print("X={}, B={}".format(mid, B))

        # Bの転倒数を求める
        def mergeSort(l, r):
            """
            数列Bの[l, r)の範囲をマージソートし、転倒数を返す
            """
            #print(l, r, B)
            if r - l == 1: return 0
            cnt = 0
            m = (l + r) // 2
            cnt += mergeSort(l, m)
            cnt += mergeSort(m, r)
            B_left = B[l:m]
            B_right = B[m:r]
            #print("B_left={}, B_right={}".format(B_left, B_right))
            left_edge = 0
            right_edge = 0
            edge = l
            while edge < r:
                if left_edge == m - l:
                    B[edge] = B_right[right_edge]
                    right_edge += 1
                elif right_edge == r - m:
                    B[edge] = B_left[left_edge]
                    left_edge += 1
                elif B_left[left_edge] > B_right[right_edge]:
                    B[edge] = B_right[right_edge]
                    right_edge += 1
                    cnt += (m - l) - left_edge
                else:
                    B[edge] = B_left[left_edge]
                    left_edge += 1
                edge += 1
            return cnt

        cnt = mergeSort(0, N + 1)
        #print("sortedB={}, cnt={}".format(B, cnt))
        #print("")
        if cnt >= (N * (N + 1) // 2) // 2 + 1: right = mid
        else: left = mid
    print(left)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def solve(n, a):
    v = []
    total = 0
    for i in range(n):
        num = (i+1) * (n-i)
        total += num
        v.append((a[i], num))
    num = 0
    target = total // 2
    position = 0
    for x, num in v:
        if position <= target <= position + num:
            return x
        position += num
    return -1

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

Submission status: Wrong Answer

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

a.sort()
for ai in a:
    ai + 1
print(a[n//2])

Submission status: Wrong Answer

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

cand=[]
if n%2==0:
    for i in range(n//2):
        if i==0:
            cand.append(1)
        else:
            cand.append(cand[-1]+2)
    for i in range(n//2,n):
        cand.append(cand[n-i-1]+1)
else:
    for i in range(n//2+1):
        if i==0:
            cand.append(1)
        else:
            cand.append(cand[-1]+2)
    for i in range(n//2+1,n):
        cand.append(cand[n-i-1]+1)
ans=list(map(list,zip(a,cand)))
#print(ans)
ans.sort()
x,y=[i[0] for i in ans],[i[1] for i in ans]
l=n*(n-1)//2+n
z=l//2+1
from itertools import accumulate
#print(ans)
ac=list(accumulate(y,func=lambda a,b: a+b))
#print(ac)
for i in range(n):
    if ac[i]>=z:
        print(x[i])
        break

Submission status: Wrong Answer

Solution code:
class BIT:
    '''
    1-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-1)

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

n = int(input())
m = n * (n - 1) // 4
a = list(map(int, input().split()))
d = dict()
_a = sorted(set(a + [0]))
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+1 for x in b] 
  bit = BIT(max(b) + 2)
  ans = 0
  for x in b:
    ans += bit.bitsum(x)
    bit.bitadd(x, 1)
  return ans >= m

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

Submission status: Wrong Answer

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) // 4
a = list(map(int, input().split()))
d = dict()
_a = sorted(set(a + [0]))
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(max(b) + 2)
  ans = 0
  for x in b:
    ans += bit.bitsum(x + 1)
    bit.bitadd(x, 1)
  return ans >= m

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