Problem:


Score : 700 points

Problem Statement

N problems are proposed for an upcoming contest. Problem i has an initial integer score of A_i points.

M judges are about to vote for problems they like. Each judge will choose exactly V problems, independently from the other judges,
and increase the score of each chosen problem by 1.

After all M judges cast their vote, the problems will be sorted in non-increasing order of score, and the first P problems will be chosen for the problemset.
Problems with the same score can be ordered arbitrarily, this order is decided by the chief judge.

How many problems out of the given N have a chance to be chosen for the problemset?

Constraints

2 \le N \le 10^5

1 \le M \le 10^9

1 \le V \le N - 1

1 \le P \le N - 1

0 \le A_i \le 10^9

Input

Input is given from Standard Input in the following format:

N M V P
A_1 A_2 ... A_N

Output

Print the number of problems that have a chance to be chosen for the problemset.

Sample Input 1

6 1 2 2
2 1 1 3 0 2

Sample Output 1

5

If the only judge votes for problems 2 and 5, the scores will be 2 2 1 3 1 2.
The problemset will consist of problem 4 and one of problems 1, 2, or 6.

If the only judge votes for problems 3 and 4, the scores will be 2 1 2 4 0 2.
The problemset will consist of problem 4 and one of problems 1, 3, or 6.

Thus, problems 1, 2, 3, 4, and 6 have a chance to be chosen for the problemset. On the contrary, there is no way for problem 5 to be chosen.

Sample Input 2

6 1 5 2
2 1 1 3 0 2

Sample Output 2

3

Only problems 1, 4, and 6 have a chance to be chosen.

Sample Input 3

10 4 8 5
7 2 3 6 1 6 5 4 6 5

Sample Output 3

8



Sample input:
6 1 2 2
2 1 1 3 0 2


Sample output:
5

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり


N,M,V,P = MI()
A = [0] + LI()
A.sort()


def f(i):  # i番目の問題が採用されうるか
    a = A[i]
    v = V-i  # 下位i人に全員が投票
    if A[-P] > a+M:
        return False
    v -= P-1  # 上位P-1人に全員が投票
    if sum(a+M-A[j] for j in range(i+1,N-P+2)) >= M*v:
        return True
    return False


left = 0
right = N
while left + 1 < right:
    mid = (left + right)//2
    if f(mid):
        right = mid
    else:
        left = mid

print(N+1-right)

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり


N,M,V,P = MI()
A = [0] + LI()
A.sort()


def f(i):  # i番目の問題が採用されうるか
    a = A[i]
    v = V-i
    if A[-P] > a+M:
        return False
    v -= P-1
    if sum(a+M-A[j] for j in range(i+1,N-P+2)) >= M*v:
        return True
    return False


left = 0
right = N
while left + 1 < right:
    mid = (left + right)//2
    if f(mid):
        right = mid
    else:
        left = mid

print(N+1-right)

Submission status: Accepted

Solution code:
n,m,v,p=map(int,input().split())
a=list(map(int,input().split()))
a.sort(reverse=True)
def judge(i):
	border=a[i]+m
	ok=min((n-i)+(p-1),n)
	if ok>=v:
		return border>=a[p-1]
	if border<a[p-1]:
		return False
	lis=[x for x in a[p-1:i]]
	cnt=0
	for i in range(len(lis)):
		cnt+=min(border-lis[i],m)
	return cnt>=(v-ok)*m

l=0
r=n
while r-l>1:
	mid=(l+r)//2
	if judge(mid):
		l=mid
	else:
		r=mid
print(l+1)

Submission status: Accepted

Solution code:
from bisect import bisect as list_bisect
max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

def bisect(ng, ok, judge, eps=1):
    while abs(ng-ok) > eps:
        m = (ng+ok)//2
        if judge(m):
            ok = m
        else:
            ng = m
    return ok

N,M,V,P = map(int,input().split())
A = sorted(map(int,input().split()))

k = N-P
def judge(i):
    if i >= k:
        return True
    a = A[i]
    if a+M < A[k]:
        return False

    r = 0
    for v in A[i+1:k+1]:
        r += a+M-v
    return r >= (V-P-i)*M

i = bisect(-1,N-1,judge)
print(N-i)

Submission status: Accepted

Solution code:
# 【考察】
# 0-indexedで考える。Aは降順ソートして考える。
# まず、初期状態でTop Pに含まれる問題はすべて出題されうる。
# なので初期でTop q (q > P)の問題が出題されるか否かを考えていく。
# 最終的にTop Pに入れるか否かが問題なので、Top 1 ~ P-1の問題は無視。
# Top qの問題に毎回投票しつつ、Top P ~ q-1の問題になるべく投票しないようにしたい。
# そこで数列 A[P], A[P+1], ..., A[q-1] を考える。
# この中から最大でN-V個の数字を選んで1減らすことをM回繰り返し、
# すべてA[q]以下にすることができればTop qの問題は出題されうる。
# 当然A[P]-A[q] > Mだったら無理（出題されない）。
# 以後A[P]-A[q] <= Mとする。
# この時、(A[P]-A[q]) + (A[P+1]-A[q]) + ... + (A[q-1]-A[q]) <= M * (N-V) であればTop qのは出題可能。
# 整理すると A[P] + A[P+1] + ... + A[q-1] <= M * (N-V) + A[q] * (q-P) となるので、
# Aの累積和のデータを保持しておけば各qにおいてO(1)で出題可否が判定可能。


def main():
    N, M, V, P = list(map(int, input().split()))
    A = list(map(int, input().split()))
    P -= 1  # to 0-indexed
    A.sort(reverse=True)  # 降順ソート
    cumsum = [0] * N
    cumsum[0] = A[0]
    for i in range(1, N):
        cumsum[i] = cumsum[i - 1] + A[i]
    q = P + 1
    while q < N:
        left = cumsum[q - 1]
        if P > 0:
            left -= cumsum[P - 1]
        right = M * (N - V) + A[q] * (q - P)
        if A[P] - A[q] > M or left > right:
            print(q)
            return
        q += 1
    print(q)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def isok(a,idx):##適宜変更
    if a+m<ap:
        return False
    elif idx<=p:
        return True
    tmp = 0 #a+mを超えないように割り振れる最大値
    for i in range(n-1,-1,-1):
        if a+m<A[i] or i<p-1:break
        tmp+= min(a+m - A[i],m)
    tmp-=m#自分自身
    #print(a,tmp)
    return  tmp>=(v-p)*m

def bisect(ls): ##valの関数isok(x,val)がTrueとなる一番右のindex を返す 全部Falseなら-1,Trueならlen(ls)-1
    ok = -1
    ng = len(ls)
    x = (ok+ng)//2
    while ng-ok>1:
        num = ls[x]
        if isok(num,x):
            ok = x
        else:
            ng = x
        x = (ok+ng)//2
    return ok ##一番右のTrueのindex  Trueの個数はok+1こ

n,m,v,p = ma()
A = lma();A.sort(reverse=True)
#print(A)
ap = A[p-1]
ans = bisect(A)+1
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
#from numba import jit

INF = 1 << 50
EPS = 1e-8
mod = 10 ** 9 + 7

def check(k, A, N, M, V, P):
    #print(k, 'start')
    VAL = A[k] + M
    if VAL < A[P]:
        return False
    if P + N-k >= V:
        return True
    #print('check1')
    checked_arr = A[P:k]
    members = V - P - N + k
    MM = M

    if M * members <= VAL * len(checked_arr) - sum(checked_arr):
        return True
    else:
        return False

def run():
    N, M, V, P, *A = map(int, read().split())

    A = sorted(A)
    A.append(-INF)
    A = A[::-1]
    l = 1
    r = N
    while r-l > 1:
        #print(l, r)
        x = (r + l) // 2
        if check(x, A, N, M, V, P):
            l = x
        else:
            r = x

    #print('last, ', l, r)
    if check(r, A, N, M, V, P):
        print(r)
    else:
        print(l)





if __name__ == "__main__":
    run()

Submission status: Accepted

Solution code:
import sys
import math
import copy
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
# sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def judge(n, m, v, p, nums, idx):
    if idx >= n - p:
        return True
    cur = nums[idx] + m
    cnt = 0
    for i in range(0, n):
        if idx == i:
            continue
        if i > n - p:
            break
        comp = nums[i]
        if comp > cur:
            return False
        cnt += min(m, cur - comp)
    # print(idx, cnt)
    if cnt >= m * (v - p):
        return True
    else:
        return False


def solve():
    n, m, v, p = getList()
    nums = getList()
    nums.sort()
    mn = 0
    mx = n-1
    while(mx - mn > 1):
        mid = (mx + mn) // 2
        if judge(n, m, v, p, nums, mid):
            mx = mid
        else:
            mn = mid

    if judge(n, m, v, p, nums, mn):
        ans = mn
    else:
        ans = mx
    # print(nums)
    # print(ans)
    print(n - ans )

def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():

    N, M, V, P = in_nn()
    A = sorted(in_nl())[::-1]

    # print(A)

    def is_ok(i):
        if i < P:
            return True
        else:
            baf = 0
            for j in range(N):
                if j < P - 1 or i <= j:
                    baf += M
                    continue

                if A[i] + M - A[j] < 0:
                    return False
                else:
                    baf += A[i] + M - A[j]

            # print(i, baf, V * M)
            return V * M <= baf

    def bisect(ng, ok):

        while abs(ok - ng) > 1:
            mid = (ok + ng) // 2
            if is_ok(mid):
                ok = mid
            else:
                ng = mid
        return ok

    ans = bisect(N, 0) + 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def is_ok(index):
  s=0
  for i in range(p-1,index):
    s+=a[index]+m-a[i]
  return s+m*(n-index+p-1)>=m*v and a[index]+m>=a[p-1]
def binary_search(a):
  ok=-1
  ng=len(a)
  while abs(ng-ok)>1:
    mid=(ng+ok)//2
    if is_ok(mid):ok=mid
    else:ng=mid
  return ok+1
n,m,v,p=map(int,input().split())
a=sorted(list(map(int,input().split())))[::-1]
print(binary_search(a))

Submission status: Accepted

Solution code:
import sys
from copy import deepcopy

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    def meguru_bisect(ok, ng):
        while abs(ok - ng) > 1:
            mid = (ok + ng) // 2
            if is_ok(mid):
                ok = mid
            else:
                ng = mid
        return ok

    def is_ok(x):
        B = deepcopy(A)
        total = m * v
        target = B[x] + m
        for i in range(n):
            if i <= x:
                B[i] += m
                total -= m
            else:
                if n - (p - 1) <= i:
                    B[i] += m
                    total -= m
                else:
                    if B[i] > target:
                        return False
                    else:
                        total -= target - B[i]
                        B[i] = target
        return total <= 0

    n, m, v, p = map(int, input().split())
    A = sorted(list(map(int, input().split())))
    ng, ok = n, -1
    res = meguru_bisect(ng, ok)
    print(n - res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
n,m,v,p = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse = True)
ans = p
border = a[p-1]
to_border = 0
for i in range(p,n):
    new_border = a[i] + m
    if new_border < border:
        print(ans)
        exit()
    possible_votes = 0
    possible_votes += (n+p-i-1)*m
    possible_votes += to_border
    possible_votes += (new_border-border)*(i-p+1)
    if possible_votes >= m*v:
        ans += 1
        to_border += border-a[i]
    else:
        print(ans)
        exit()
print(ans)
exit()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    import bisect

    n, m, v, p = map(int, readline().split())
    a = list(map(int, readline().split()))

    a.sort()

    ng = -1
    ok = max(0, n - p)

    while abs(ng - ok) > 1:
        mid = (ng + ok) // 2
        cur = a[mid] + m
        c = n - bisect.bisect_right(a, cur)
        if c >= p:
            ng = mid
            continue
        rem = v - (mid + 1 + p - 1)
        score = m * rem
        for x in a[mid + 1:n - p + 1]:
            if x > cur:
                score -= m
            else:
                score -= cur - x
        if score <= 0:
            ok = mid
        else:
            ng = mid

    print(n - ok)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, M, V, P = map(int, input().split())

As = [10**9+1] + list(map(int, input().split()))

As.sort(reverse=True)


rlt = P
memo = [0]*(N+1)

for i in range(P+1,N+1):
  memo[i] = memo[i-1] + As[i-1]

for i in range(P+1,N+1):
  if As[i] == As[i-1]:
    rlt += 1
    continue
  if As[i] + M < As[P]:
    break
  if N - i >= V - P:
    rlt += 1
  else:
    t = i - P
    v = V - N + t
    if t*(As[i]+M) - memo[i] >= M*v:
      rlt += 1
    else:
      break
      
print(rlt)

Submission status: Accepted

Solution code:
n, m, v, p = map(int, input().split())
alst = list(map(int, input().split()))
alst.sort(reverse = True)
left = p - 1
right = n
while right - left > 1:
    pos = (left + right) // 2
    if alst[pos] + m < alst[p - 1]:
        right = pos
        continue
    cnt = (p - 1) * m
    base = alst[pos] + m
    for i in range(p - 1, n):
        cnt += min(m, base - alst[i])
    if cnt >= m * v:
        left = pos
    else:
        right = pos
print(left + 1)

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり

N,M,V,P = MI()
A = [0] + LI()
A.sort()

from bisect import bisect_left


def f(n):  # 下からn番目のスコアの問題が、採用される可能性があるか
    v = V-n  # スコア下位n問には全員が投票したとしてよい
    if A[n] + M < A[-P]:  # 上位P人に入れない
        return False
    else:
        v -= P-1  # スコア上位P-1人には全員が投票したとしてよい
        if v <= 0:
            return True
        else:
            if sum(A[n]+M-A[i] for i in range(n+1,N-P+2)) >= M*v:
                return True
            else:
                return False


left = 0  # 採用される可能性なし
right = N  # 採用される可能性あり
while left + 1 < right:
    mid = (left + right)//2
    if f(mid):
        right = mid
    else:
        left = mid

print(N+1-right)

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり

N,M,V,P = MI()
A = [0] + LI()
A.sort()

from bisect import bisect_left


def f(n):  # 下からn番目のスコアの問題が、採用される可能性があるか
    v = V-n  # スコア下位n問には全員が投票したとしてよい
    m = bisect_left(A,A[n]+M+1)
    if N-m+1 >= P:  # 上位P人に入れない
        return False
    else:
        v -= P-1  # スコア上位P-1人には全員が投票したとしてよい
        if v <= 0:
            return True
        else:
            if sum(A[n]+M-A[i] for i in range(n+1,N-P+2)) >= M*v:
                return True
            else:
                return False


left = 0  # 採用される可能性なし
right = N  # 採用される可能性あり
while left + 1 < right:
    mid = (left + right)//2
    if f(mid):
        right = mid
    else:
        left = mid

print(N+1-right)

Submission status: Accepted

Solution code:
n, m, v, p = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse=True)
l, r = 0, n
while r - l > 1:
    mid = (l + r) // 2
    cnt = 0
    for i in range(n):
        if i < p - 1 or i >= mid + 1:
            cnt += m
        else:
            cnt += a[mid] + m - a[i]
    if mid <= p - 1 or (a[mid] + m >= a[p - 1] and cnt >= m * v):
        l = mid
    else:
        r = mid
print(r)

Submission status: Accepted

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

n, m, v, p = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse = True)

def f(x):
    if x < p:
        return True
    if a[p-1] > a[x] + m:
        return False
    else:
        res = m * v
        res -= m * (n-x)
        res -= m * (p-1)
        for i in range(p-1, x):
            res -= min(m, max(0,a[x]+m-a[i]))
        return res <= 0

ok = 0
ng = n
while ng - ok > 1:
    nw = (ok+ng) // 2
    if f(nw):
        ok = nw
    else:
        ng = nw
print(ng)

Submission status: Accepted

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

n, m, v, p = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse = True)

def f(x):
    if x < p:
        return True
    if a[p-1] > a[x] + m:
        return False
    else:
        cnt = m * ((n-x)+(p-1))
        for i in range(p-1, x):
            cnt += min(m, max(0,a[x]+m-a[i]))
        return cnt >= m*v

ok = 0
ng = n
while ng - ok > 1:
    nw = (ok+ng) // 2
    if f(nw):
        ok = nw
    else:
        ng = nw
print(ng)

Submission status: Accepted

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

n, m, v, p = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse = True)

def f(x):
    if x < p:
        return True
    if a[p-1] > a[x] + m:
        return False
    else:
        cnt = m * ((n-x)+(p-1))
        for i in range(p-1, x):
            cnt += max(0,a[x]+m-a[i])
        return cnt >= m*v

ok = 0
ng = n
while ng - ok > 1:
    nw = (ok+ng) // 2
    if f(nw):
        ok = nw
    else:
        ng = nw
print(ng)

Submission status: Accepted

Solution code:
n,m,v,p = map(int, input().split())
As = list(map(int, input().split()))
As.sort(reverse=True)
# print(As)
def f(x):
    # 判定基準
    if x < p:
        return True
    if As[x]+m < As[p-1]:
        return False
    cnt0 = (n-x)*m
    cnt1 = (p-1)*m
    cnt2 = 0
    for i in range(p-1, x):
        cnt2 += As[x]+m-As[i]
    return cnt0 + cnt1 + cnt2 >= m*v    


# 二部探索でOK/NG求める
ok = 0
ng = n
while ng - ok > 1:
    mid = (ok+ng)//2
    if f(mid):
        ok = mid
    else:
        ng = mid
print(ok+1)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############
def ACC1(l):
  N = len(l)
  ret = [0]*(N+1)
  for i in range(N):
    ret[i+1] = ret[i]+l[i]
  return ret

N,M,V,P = IL()
A = IL()
A.sort()
ACC = ACC1(A)

Border = A[N-P]

def is_ok(x):
  if x >= Border:
    return True
  else:
    p = bisect.bisect(A,x)
    x = A[max(p-1,0)]
    left = (V-1)-(P-1)-max(p-1,0)
    reach = x + M
    if reach < Border:
      return False
    else:
      mizohaba = (N-1)-(P-1)-max(p-1,0)
      sowa = ACC[N-P+1]-ACC[max(p,1)]
      if left*M <= mizohaba*reach-sowa:
        return True
      else:
        False

def meguru_bisect(ng, ok):
  while (abs(ok - ng) > 1):
    mid = (ok + ng) // 2
    if is_ok(mid):
      ok = mid
    else:
      ng = mid
  return ok

ans = meguru_bisect(-10**9-1,10**9+1)

print(N-bisect.bisect(A,ans-1))

Submission status: Accepted

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

A.sort()
C = [0] * (n+1)
for i in range(n):
  C[i+1] = C[i] + A[i]
  
ans = 0
for i in range(n):
  x = A[i] + m
  if x < A[-p]:
    continue
  if (v-p-i) > 0:
    u = (v-p-i) * m
    if u <= x * (n-p-i) - C[n-p+1] + C[i+1]:
      ans += 1
  else:
    ans += 1
    
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
N, M, V, P = [int(_) for _ in input().split()]
A = np.array([int(_) for _ in input().split()], dtype=int)
A.sort()


def check(idx):
    a = A[idx]
    # idx問目(0-indexed)を勝たせられるかどうか
    # M回すべてidx問目であればa→a+M
    # A[:idx]とA[N-P+1:]はM回全て選択したとしてもidx問目の可否が悪化することは無い
    # 　N-P+1<=idxであれば必ずOK
    # 　A[idx]+M<A[N-P]であれば必ずNG
    # A[idx+1:N-P+1]から(V-P-idx)個をM回選択したときの総数<=(a+M)*(N-P-idx)であればOK
    if N - P + 1 <= idx:
        return True
    elif a + M < A[N - P]:
        return False
    else:
        return sum(A[idx + 1:N - P +
                     1]) + (V - P - idx) * M <= (a + M) * (N - P - idx)


lb = -1
rb = N
# Min x for check(x) == True
while rb - lb > 1:
    mid = (rb + lb) // 2
    if check(mid):
        rb = mid
    else:
        lb = mid
print(N - rb)

Submission status: Accepted

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n,m,v,p = map(int,ipt().split())
    a = [int(i) for i in ipt().split()]
    a.sort(reverse=True)
    l = p
    r = n
    while l < r:
        mid = l + (r-l)//2
        tp = a[mid]+m
        if a[p-1] > tp:
            r = mid
        else:
            if p+n-mid-1 >= v:
                l = mid+1
            else:
                res = v+mid+1-n-p
                cos = 0
                for i in range(p-1,mid):
                    cos += tp-a[i]
                if cos >= res*m:
                    l = mid+1
                else:
                    r = mid
    print(l)

    return

if __name__ == '__main__':
    main()

Submission status: Accepted

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

a.sort(reverse = True)

ok = 0
ng = n

while ng - ok > 1:
    mid = ok + (ng-ok)//2
    get = a[mid] + m
    flag = 1
    if get < a[p-1]:
        flag = 0

    cap = 0
    for i in range(n):
        if i < p-1:
            cap += m
        elif mid <= i:
            cap += m
        else:
            cap += max(get - a[i], 0)
    if cap < m*v:
        flag = 0

    if flag:
        ok = mid
    else:
        ng = mid

print(ok+1)

Submission status: Accepted

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

A.sort(reverse = True)

def solve(n):
    
    if n < P:
        return True
    
    if A[P-1] > A[n] + M:
        return False
    
    cnt = M * (P - 1 + N - n)
    for i in range(P-1,n):
        cnt += max(0, A[n] + M - A[i])
    
    return cnt >= M * V

left = 0
right = N

while left + 1 < right:
    mid = (left + right) // 2
    if solve(mid):
        left = mid
    else:
        right = mid

print(right)

Submission status: Accepted

Solution code:
N, M, V, P = map(int, input().split())
A = sorted(list(map(int, input().split())), reverse=True)
BORDER = A[P - 1]

# にぶたん: x番目の問題が採用される可能性があるか？
ok, ng = 0, N
while abs(ok - ng) > 1:
    x = (ok + ng) // 2
    x_score = A[x] + M
    remain_vote = M * (V - 1)

    if x_score < BORDER:
        ng = x
        continue

    for i, a in enumerate(A):
        if i == x:
            continue
        elif i < P and A[i] > BORDER:
            remain_vote -= M
        else:
            remain_vote -= min(M, x_score - a)

    if remain_vote <= 0:
        ok = x
    else:
        ng = x

print(ok + 1)

Submission status: Accepted

Solution code:
N,M,V,P=map(int,input().split())
A=list(map(int,input().split()))
A=sorted(A)[::-1]
P-=1
def f(x):
  if x<=P:
    return True
  elif A[x]+M<A[P]:
    return False
  c=0
  for i in range(N):
    if i<P or i>=x+1:
      c+=M
    else:
      c+=A[x]+M-A[i]
  return c>=M*V

l,r=0,N
while l+1!=r:
  m=(l+r)//2
  if f(m):
    l=m
  else:
    r=m
print(l+1)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
import numpy as np
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, M, V, P = MAP()
P -= 1
A = LIST()
A.sort(reverse=True)

def judge(x):
    if x <= P:
        return True
    elif A[x]+M < A[P]:
        return False
    cap = 0
    for i in range(N):
        if i < P or i >= x+1:
            cap += M
        else:
            cap += A[x]+M-A[i]
    return cap >= M*V

l = 0
r = N

while l+1 != r:
    m = (l+r)//2

    if judge(m):
        l = m
    else:
        r = m
print(l+1)

Submission status: Accepted

Solution code:
n,m,v,p = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)
ok = p-1
ng = n
def solve(x):
    if a[x] + m < a[p-1]:
        return False
    now = 0
    for i in range(n):
        if i >= x:
            now += m
        elif i < p-1:
            now += m
        else:
            now += a[x] + m - a[i]
    if now >= m*v:
        return True
    else:
        return False

while ng - ok > 1:
    mid = (ng + ok)//2
    if solve(mid):
        ok = mid
    else:
        ng = mid

print(ok+1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, M: int, V: int, P: int, A: "List[int]"):
    P -= 1
    A = sorted(A, reverse=True)

    result = 0

    cumsum = [0 for i in range(N+1)]
    for n in range(N-1):
        cumsum[n+1] = A[n] + cumsum[n]

    for n in range(N):
        if n < P:
            result += 1
        elif A[n] + M < A[P]:
            continue
        else:
            affords = M * V - M - M * (P-1)
            if affords <= 0:
                result += 1
                continue
            
            sunmmation = A[n] * (n-P) + M * (n-P) - (cumsum[n] - cumsum[P])
            affords -= sunmmation
            affords -= (N-n) * M

            if affords <= 0:
                result += 1
                continue
    print(result)
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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
    M = int(next(tokens))  # type: int
    V = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, M, V, P, A)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def func(a, idx, m, v, p):
    if len(a) - idx <= p:
        return True
    if a[idx] + m < a[-p]:
        return False
    lim = 0
    for i in range(len(a)):
        if i <= idx:
            lim += m
        elif i <= len(a)-p:
            lim += a[idx] + m - a[i]
        else:
            lim += m
    if lim >= m*v:
        return True
    else:
        return False

def main():
    n, m, v, p = map(int, input().split())
    a = list(map(int, input().split()))
    a.sort()
    L, R = -1, n-1
    while L+1 < R:
        P = (L+R)//2
        if func(a, P, m, v, p):
            R = P
        else:
            L = P
    print(n-R)

if __name__ == "__main__":
    main()