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:
n,m,v,p = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse=True)

def check(mid):
    remain = v*m
    more = 0
    less = 0
    same = 0
    tmp = [0]
    for i in range(n):
        if a[i]+m <= a[mid]+m:
            less += 1
            remain -= m
        elif a[i]<=a[mid]+m:
            same += 1
            remain -= a[mid]+m-a[i]
            tmp.append(tmp[-1] + a[i]-a[mid])
        else:
            more += 1
            remain -= m
    if more >= p:
        return False
    if remain <= 0:
        return True
    hoge = p-more-1
    if (len(tmp) >= hoge+1 and tmp[hoge] >= remain) or (len(tmp) < hoge+1 and tmp[-1] >= remain):
        return True
    return False

left = 0
right = n
while right-left > 1:
    mid = (right+left)//2
    if check(mid):
        left = mid
    else:
        right = mid

print(left+1)

Submission status: Accepted

Solution code:
def check(n):
    x = A[n] + M
    if P == 1:
        B = A[:n] + A[n+1:]
    else:
        B = A[:n] + A[n+1:-(P-1)]
    scores = M * (V - P)
    if x < B[-1]:
        return False
    for b in B:
        if b + M <= x:
            scores -= M
        else:
            scores -= x - b
        if scores <= 0:
            return True
    return False


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

left = 0
right = N - P
while left < right:
    mid = (left+right) // 2
    if check(mid):
        right = mid
    else:
        left = mid + 1
print(N - left)

Submission status: Accepted

Solution code:
def check(i, N, M, V, P, A):
    K = N - V
    tot = sum(A[(P-1):i]) - A[i]*(i-(P-1))
    if K*M >= tot and (A[P-1]-A[i])<=M:
        return True
    else:
        return False

N, M, V, P = map(int,input().split())
A = [int(i) for i in input().split()]
A.sort(reverse=True)

start = P
end = N-1
if check(end, N, M, V, P, A):
    print(N)
elif not check(start, N, M, V, P, A):
    print(P)
else:
    while True:
        if (end - start) == 1:
            break
        new = (start + end)//2
        flag = check(new, N, M, V, P, A)
        if flag:
            start = new
        else:
            end = new
    print(start+1)

Submission status: Accepted

Solution code:
n,m,v,p=map(int,input().split())
a=list(map(int,input().split()))
a.sort(reverse=1)
#print(a)
se=set()
for i in range(p):se.add(a[i])

s=a[p-1]
for i in range(p,n):
  x=max(v-(n-((i+1)-(p-1)))-1,0)
  if a[i]+m>=max(0--(s+m*x)//(i-p+1),a[p-1]):se.add(a[i])
  #print(i,x,s+m*x,s,0--(s+m*x)//(i-p+1))
  s+=a[i]

ans=0
for i in a:
  if i in se:ans+=1
print(ans)

Submission status: Accepted

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

a.sort()
a = a[::-1]

s = [0] * p
for i in range(p, n + 1):
    s.append(s[-1] + a[i - 1])
s = s[1:]

ans = 0
for i in range(1, n + 1):
    if i <= p:
        ans += 1
    else:
        if v - 1 <= p - 1:
            if a[i - 1] + m >= a[p - 1]:
                ans += 1

        else:
            if v - p <= n - i:
                if a[i - 1] + m >= a[p - 1]:
                    ans += 1
            else:
                if a[i - 1] + m < a[p - 1]:
                    continue
                elif a[i-1] * (i - p) >= m * (v - n) + s[i - 2]:
                    ans += 1

print(ans)

Submission status: Accepted

Solution code:
import math
import fractions

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)

    # divisors.sort()
    return divisors

def bitlist(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

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


n,m,v,p = list(map(int, input().split()))
aa = list(map(int, input().split()))
a = [[aa[i],i+1] for i in range(n)]

a.sort(key=lambda x:x[0])
#print(a)
b = [a[i][0] for i in range(n)]
anum = [a[i][1] for i in range(n)]
#print(anum)

sums = []
now = 0
for i in range(n):
    now += b[i]
    sums.append(now)
#print(sums)
ans = 0

firstMove = 1
for i in range(100):
    if(firstMove < n/2+0.1):
        firstMove*=2
    else:
        break

migis = []
'''
#print(firstMove)
for i in range(n):
    tall = b[i]+m
    #print("tall",tall)
    now = i
    move = firstMove
    while(move!=0):
        if(now+move < n):
            if(tall >= b[now+move]):
                now += move
        move = move//2
        #print(i,now)
    migis.append(now)
#print(migis)
'''
for i in range(n):
    if(i >= n-p):
        ans+=1
        continue
    if(b[i]+m < b[n-p]):
        continue
    k = b[i]+m
    amount = 0
    amount += m * (i+1)
    #print("--------roop:",i)
    #print("a+=",m*(i+1))
    amount += m * (p-1)
    #print("a+=",m*(p-1))
    amount += (b[i]+m)*(n-p-i)-(sums[n-p]-sums[i])
    #print("tttttt")
    #print(b[i]+m,n-p-i,sums[n-p],sums[i])
    #print("a+=",(b[i]+m)*(n-p-i)-(sums[n-p]-sums[i]))
    #print(amount,m*v)
    if(amount < m*v):
        continue
    else:
        ans+=1
        #print("ba:",i)
        continue

print(ans)

Submission status: Accepted

Solution code:
n,m,v,p=map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)
reva = [a[0] - x for x in a]
ub = a[0]
lb = a[-1]

from bisect import *

def ok(val):
    i = bisect_left(reva,a[0]-val)
    val = a[i]
    if v-(min(n-i,v)) < p and a[p-1] <= a[i] + m:
        return True
    l = v - (p-1) - (n - i)
    if a[i]+m < a[p-1]:
        return False
    if sum(list(map(lambda x:min(a[i]+m-x,m),a[p-1:i]))) >= l*m:
        return True
    return False

while ub > lb:
    mid = (ub+lb)//2
    if ok(mid):
        ub=mid
    else:
        lb=mid+1

print(len(list(filter(lambda x:x >= lb,a))))

Submission status: Accepted

Solution code:
def solve(n, m, v, p, a_list):
    a_list_s = sorted(a_list, reverse=True)
    # member
    # vote: v
    # problem: p
    base_bar = a_list_s[p - 1]
    res = p
    space = 0
    for i in range(p, n):
        if a_list_s[i] + m - base_bar < 0:
            break
        space_now = space + (a_list_s[i] + m - base_bar) * (i - p + 1)
        v_now = max(v - (n - i) - (p - 1), 0)
        if space_now >= v_now * m:
            res += 1
        space += base_bar - a_list_s[i]

    return res


def main():
    n, m, v, p = map(int, input().split())
    a_list = list(map(int, input().split()))
    res = solve(n, m, v, p, a_list)
    print(res)


def test():
    assert solve(6, 1, 2, 2, [2, 1, 1, 3, 0, 2]) == 5
    assert solve(6, 1, 5, 2, [2, 1, 1, 3, 0, 2]) == 3
    assert solve(10, 4, 8, 5, [7, 2, 3, 6, 1, 6, 5, 4, 6, 5]) == 8


if __name__ == "__main__":
    test()
    main()

Submission status: Accepted

Solution code:
N,M,V,P=[int(a) for a in input().split()]
A=[int(a) for a in input().split()]
effect=N-V
A.sort(reverse=True)
#print(A)
ans=P
target_score=A[P-1]
target_vote=0
to_kill=0
#print(target_score)
for i in range(P,N):
    if A[i-1]>A[i]:
        #print(i,target_vote)
        target_vote+=(A[i-1]-A[i])*(i-P+1)
        to_kill=i-P+1
        #print(i,target_vote)
    real_effect=min(effect,to_kill)
    #print(i,target_vote,real_effect)
    if target_vote==0 or (((target_vote-1)//real_effect)+1<=M and target_score-A[i]<=M):
        ans+=1
    #print(ans)
print(ans)

Submission status: Accepted

Solution code:
import bisect
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N, M, V, P = list(map(int, sys.stdin.buffer.readline().split()))
A = list(map(int, sys.stdin.buffer.readline().split()))

A.sort(reverse=True)
RA = A[::-1]


def can_choose(k):
    # A[k]が選ばれるか
    ak = A[k] + M
    greaters = N - bisect.bisect_right(RA, ak)
    if greaters >= P:
        return False
    # 自分より上位 P - 1 人には全部配る
    rem = (V - P) * M

    cnt = 0
    for i, a in reversed(list(enumerate(A))):
        if i == k:
            continue
        if rem <= 0:
            break
        rem -= min(M, ak - a)

        cnt += 1
        if cnt >= N - P:
            break
    return rem <= 0


# print(A)
# for i in range(N):
#     a = can_choose(i)
#     print(A[i], a)


ok = -1
ng = N
while abs(ok - ng) > 1:
    mid = (ok + ng) // 2
    if can_choose(mid):
        ok = mid
    else:
        ng = mid
print(ok + 1)

Submission status: Accepted

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

a.sort()
ans = p-1
end = n-p+1
loopend = n-v+1
sm = sum(a[0:end])
needed = (v - (p-1)) * m
#print(a)
for i in range(end):
    sm -= a[i]
    needed -= m
    if a[i] + m < a[end-1]:
        continue
    max_score = (a[i] + m) * (end-i-1) - sm
    #print(a[i]+m, end-i-1, sm)
    #print(max_score, needed)
    if needed <= max_score:
        ans = n-i
        break
print(ans)

Submission status: Accepted

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


def check(A, M, V, P, idx):
  # print(f'i={idx}, A={A}, M={M}, V={V}, P={P}')
  v = A[idx] + M

  if v < A[P]:
    # print(f'v={v}, False')
    return False

  n = M * (V - P - (len(A) - idx))

  if n <= 0:
    # print(f'v={v}, n={n}, True')
    return True

  r = sum(v - x for x in A[P:idx])

  # print(f'v={v}, n={n}, r={r}, {r >= n}')
  return r >= n


def main():
  _, M, V, P = map(int, input().split())
  A = sorted(list(map(int, input().split())), reverse=True)
  P -= 1

  if check(A, M, V, P, len(A) - 1):
    print(len(A))
    return

  low = P
  high = len(A) - 1

  while (high - low) > 1:
    idx = (low + high) // 2
    ret = check(A, M, V, P, idx)

    if ret:
      low = idx
    else:
      high = idx

  print(high)


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)
ans=p
S=[A[p-1]]
for i in range(p,n):
    S.append(S[-1]+A[i])
for i in range(p,n):
    if v<=p+n-i-1:
        if A[p-1]-A[i]<=m:
            ans+=1
    else:
        if A[p-1]-A[i]<=m and S[i-p]-A[i]*(i-p+1)<=(n-v)*m:
            ans+=1
        else:
            break
print(ans)

Submission status: Accepted

Solution code:

N,M,V,P = map(int,input().split())
A = list(map(int,input().split()))
#%%
As = sorted(A)
border = As[-P]
upbound = N-P
lowbound = N-P
while As[upbound] == border:
    upbound += 1
    if upbound > N-1:break
while As[lowbound] == border:
    lowbound -= 1
    if lowbound < 0:break

upbound -= 1
lowbound += 1
    
def isOK(mid):
    if mid>= lowbound: return True
    if mid==N-1: return True
    if (border-As[mid])>M:
        return False
    
    S = sum(As[mid+1:upbound+1])-As[mid]*(upbound-mid)
    U = M*(N-V)
    if S>U:
        return False
    else:
        return True

def bsearch():
    ng = -1
    ok = N
    while abs(ok-ng)>1:
        mid = (ok+ng)//2
        if isOK(mid):
            ok = mid
        else :
            ng = mid
    return ok


key = bsearch()

print(N-key)

Submission status: Accepted

Solution code:
n,m,v,p = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)
c = a[p-1]
#print(a)

b = 0
d = 0
ans = 0
for i in range(n):
  if i < p-1:
    ans += 1
    continue
  if a[i] + m < c:
    continue
  now = a[i]
  vv = v - (n-i) - (p-1)
  #print(i,a[i],vv)
  if vv <= 0 or d * (now+m) >= b + vv * m:
    ans += 1
  b += now
  d += 1
print(ans)

Submission status: Accepted

Solution code:
def judge(ind):

    maxi = A[ind] + M

    left = M * (V-1)
    over = 0
    np = P-1

    for i in range(N):
        
        if i == ind:
            continue
        
        if np > 0:
            left -= M
            np -= 1
        elif A[i] > maxi:
            return False
        else:
            left -= min(M, maxi - A[i])

    if left > 0:
        return False
    else:
        return True


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

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

A.sort()
A.reverse()

l = 0
r = N

while r - l != 1:

    mid = (l+r)//2

    if judge(mid):
        l = mid
    else:
        r = mid

print (r)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
n,m,v,p=map(int,input().split())
a_list=list(map(int,input().split()))
a_list.sort(reverse=True)
ans=p
S=0
for k in range(p+1,n+1):
    S+=a_list[k-2]
    if n-k+p>=v:
        if a_list[k-1]+m>=a_list[p-1]:
            ans+=1
    else:
        if a_list[k-1]+m>=a_list[p-1]:
            d=(k-p)*(a_list[k-1]+m)-S
            if (v-n+k-p)*m<=d:
                ans+=1
print(ans)

Submission status: Accepted

Solution code:
N,M,V,P = map(int,input().split())
A = list(map(int,input().split()))
A = sorted(A)
S = sum(A)
for i in range(P-1):
    x = A.pop()
    S -= x
total_score = M*(V-P+1)
kazu = N - P + 1
for i in range(N-P+1):
    a = A.pop(0)
    total_score -= M
    S -= a
    kazu -= 1
    T = (M+a)*kazu - S
    if i == N - P:
        ans = P
    else:
        if (a+M) >= A[-1]:
            if T >= total_score:
                ans = kazu + P
                break
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

n, m, v, p = [int(item) for item in input().split()]
a = [int(item) for item in input().split()]
a.sort()
cumsum = [0] * (n+1)
for i in range(n):
    cumsum[i+1] = cumsum[i] + a[i]

hand = n - v 
ok = [0] * (n - p)
for i in range(n - p):
    total = cumsum[n-p+1] - cumsum[i+1] - a[i] * (n - p - i)
    maxval = a[n-p] - a[i]
    turn = max((total + hand - 1) // hand, maxval)
    if m >= turn:
        ok[i] = 1
ans = sum(ok) + p
print(ans)

Submission status: Accepted

Solution code:
N,M,V,P = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
def possible(i):
    A_ = [A[i] for i in range(N)]
    rest = M*(V-1)
    A_[i] += M
    for j in range(i+1,N):
        if A_[j] <= A_[i]:
            d = min(rest,A_[i]-A_[j])
            A_[j] += d
            rest -= d
        else:
            d = min(rest,M)
            A_[j] += d
            rest -= d
        if rest == 0:
            break
    for j in range(i):
        d = min(rest,M)
        A_[j] += d
        rest -= d
        if rest == 0:
            break
    for j in range(N-1,i,-1):
        if A_[j] == A_[i]:
            d = min(rest,A[j]+M-A_[j])
            A_[j] += d
            rest -= d
        if rest == 0:
            break
    c = A_[i]
    A_.sort(reverse=True)
    return A_[P-1] <= c

l = 0
r = N-1
m = (l+r)//2
for i in range(20):
    if possible(m):
        r = m
    else:
        l = m
    m = (l+r)//2
if possible(m):
    ans = N-m
else:
    ans = N-m-1
print(ans)

Submission status: Accepted

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

def is_ok(ind):
  bigs = bisect.bisect_right(A,A[ind]+M)
  if N-bigs >= P:
    return False
  votes = M*(V-1)
  j = 0
  for i in range(N-1,-1,-1):
    if i==ind:
      continue
    if j < P-1:
      votes = max(votes-M,0)
    else:
      cur = min(A[ind]+M,A[i]+M,A[i]+votes)
      votes -= max(0,cur-A[i])
    j += 1
  if votes == 0:
    return True
  else:
    return False

lo = 0
hi = N
mid = (lo+hi)//2
while lo < hi:
  mid = (lo+hi)//2
  if is_ok(mid):
    hi = mid
  else:
    lo = mid+1
print(N-hi)

Submission status: Accepted

Solution code:
n,m,v,p = map(int,input().split())
a = list(map(int,input().split()))
a.sort(reverse=True)
k = (v-n)*m
s = k
x = a[p-1]
for i in range(p,n):
  s += a[i-1]
  if a[i] + m < x or (i-p+1)*a[i] < s:
    print(i)
    exit()
print(n)

Submission status: Accepted

Solution code:
from bisect import *
n,m,v,p=map(int,input().split())
it=list(map(int,input().split()))
it.sort()
pre=[it[0]]
for i in range(1,n):
    pre.append(pre[i-1]+it[i])
ans=0
par=[i for i in range(n)]
for i in range(n-2,-1,-1):
    if it[i]==it[i+1]:
        par[i]=par[i+1]
#print(it)

for i in range(n):
    
    if it[i]+m<it[-p]:
        continue
    ind=n-(p-1)
    ind2=par[i]
    if ind2>=ind-1:
        ans+=1
        continue

    tot=m*v
    
    tot-=(n-ind)*m
    tot-=(ind2)*m
    tot-=m
    #print(tot)
    co=pre[ind-1]-pre[ind2]
    co=((it[i]+m)*(ind-1-ind2)-co)
    
    #print(ind,ind2,tot,co)
    if co>=tot:
        ans+=1
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_right
N, M, V, P = map(int, input().split())
A = list(map(int, input().split()))
A.sort()

A_m = sorted(set(A))
n = len(A_m)
ok = n-1
ng = -1
while ng+1 < ok:
    c = (ok+ng)//2
    a = A_m[c]
    idx = bisect_right(A, a)
    if idx > N-P:
        ok = c
        continue
    if M < A[-P]-a:
        ng = c
        continue
    s = 0
    for aa in A[-P:idx-1:-1]:
        s += aa-a
    if s > M*(N-V):
        ng = c
    else:
        ok = c
a = A_m[ok]
print(sum(a<=aa for aa in A))

Submission status: Accepted

Solution code:
n,m,v,p = map(int, input().split())
a = list(map(int, input().split()))
a.sort(reverse=True)
tg = a[p-1]
l = p-1
r = n
biggest = 0
while l<r:
    x = (l+r)//2
    if a[p-1]-a[x]<=m:
        border = v*m-(n-x+p-1)*m
        biggest = sum([a[x]+m-a[j] for j in range(p-1,x)])
    else:
        r = x
        continue
    if border > biggest:
        r = x
    elif border <= biggest:
        l = x+1
print(l)

Submission status: Accepted

Solution code:
N,M,V,P=map(int,input().split())
A=list(map(int,input().split()))
A.sort(reverse=True)
ans=0
pre_num=1
dsum=0
th=A[P-1]
for i in range(P,N):
    rest_m=M*(N-V)
    p=A[i]
    if th-p>M:break
    dsum+=(A[i-1]-p)*pre_num
    pre_num+=1
    rest_m-=dsum
    if rest_m<0:break
    ans+=1
print(P+ans)

Submission status: Accepted

Solution code:
def f(k):
    if k<=P:
        return True
    if A[k]+M<A[P]:
        return False
    num=A[k]+M
    zzz=M*V-(N-k+P)*M
    if zzz<=0:
        return True
    for j in range(P,k):
        zzz-=num-A[j]
    if zzz<=0:
        return True
    else:
        return False

N,M,V,P=map(int,input().split())
A=list(map(int,input().split()))
A.sort(reverse=True)
A=[float("inf")]+A
low=1
high=N
while high-low>=1:
    mid=(high+low)//2
    if f(mid):
        if low==mid:
            if f(high):
                low=high
            else:
                high=low
        else:
            low=mid
    else:
        high=mid
print(low)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import numpy as np

N,M,V,P = map(int,readline().split())
A = np.array(read().split(),np.int64)

A.sort()

def test(i):
    """
    i 番の人を勝者にできる
    """
    # はじめから上位P以内の場合
    if N - i <= P:
        return True
    # 他人に入ることを許容できる票数を計算する
    me = A[i] + M
    C = np.zeros(N,np.int64)
    C = me - A
    C = np.minimum(C,M)
    C[N-P+1:] = M # この層は負け前提
    if (C < 0).any():
        return False
    C[i] = 0
    x = C.sum()
    return C.sum() >= M * (V-1)

left = -1 # 勝てない
right = N-1 # 勝てる
while left + 1 < right:
    x = (left + right) // 2
    if test(x):
        right = x
    else:
        left = x

answer = N - right
print(answer)

Submission status: Accepted

Solution code:
N, M, V, P = map(int, input().split())
A = sorted([int(a) for a in input().split()])
t = A[-P]
def chk(k):
    if A[k] >= t: return 1
    u = A[k] + M
    if u < t:
        return 0
    s = sum([min(M, u - A[i]) for i in range(N-P+1)])
    if s >= M * (V - P + 1):
        return 1
    return 0

l, r = -1, N-P
while r - l > 1:
    m = (l+r) // 2
    if chk(m):
        r = m
    else:
        l = m

print(N - r)

Submission status: Accepted

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

capacity = M * (N-V)
def isOK(i):
    Ai = As[i]
    s = 0
    for j in range(P-1, i):
        d = As[j] - Ai
        if d > M:
            return False
        s += d
        if s > capacity:
            return False
    return True

ok = -1
ng = N
while ng - ok > 1:
    mid = ok + (ng - ok) // 2
    if isOK(mid):
        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()

ok = N-1
ng = -1
mid = (ok+ng)//2
while ok - ng > 1:
    if mid >= N - P:
        ok = mid
        mid = (ok+ng)//2
        continue
    K = A[mid] + M
    if K < A[N - P]:
        ng = mid
        mid = (ok+ng)//2
        continue
    p = M * (V-P)
    flg = 0
    for i in range(mid):
        p -= M
        if p <= 0:
            flg = 1
            break
    if flg:
        ok = mid
        mid = (ok+ng)//2
        continue
    for i in range(mid+1, N - (P-1)):
        p -= K - A[i]
        if p <= 0:
            flg = 1
            break
    if flg:
        ok = mid
        mid = (ok+ng)//2
    else:
        ng = mid
        mid = (ok+ng)//2

print(N - ok)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7 # 998244353
input=lambda:sys.stdin.readline().rstrip()

def bisection(l,r,f,left=True,discrete=True):
    eps=1 if(discrete) else 10**-8
    if((not left)^f(r)): return r if(left) else r+1
    elif(left^f(l)): return l-1 if(left) else l
    while(r-l>eps):
        h=(l+r)//2 if(discrete) else (l+r)/2
        if((not left)^f(h)): l=h
        else: r=h
    return (l+r)/2 if(not discrete) else l if(left) else r

def resolve():
    n,m,v,p=map(int,input().split())
    A=list(map(int,input().split()))
    A.sort()

    # どの i までが採用されるかを二分探索
    def check(i):
        # プラスするのは vm ポイント
        # 0 から i までは +m する
        # n-p+1 から n-1 までは +m する
        rest=(v-(i+1)-(p-1))*m
        s=A[i]+m
        for j in range(i+1,n-p+1):
            if(s<A[j]): return False
            rest-=s-A[j]

        return rest<=0

    print(n-bisection(0,n-1,check,left=False))
resolve()

Submission status: Accepted

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

N, M, V, P = map(int, readline().split())
A = list(map(int, readline().split()))

A.sort(reverse = True)


ok = P-1
ng = N

while abs(ok-ng) > 1:
    med = (ok+ng)//2
    R = A[med] + M
    J = max(0, V - (N-med))*M
    res = 0
    for i in range(P-1):
        res += M
    for i in range(P-1, med):
        if R-A[i] < 0:
            res = -1
            break
        res += R-A[i]
    if res >= J:
        ok = med
    else:
        ng = med
print(ok+1)

Submission status: Accepted

Solution code:
N, M, V, P = map(int, input().split())
A = list(map(int, input().split()))
A.sort()
def C(x):
    a = A[x]
    m = a+M
    if m<A[N-P]:
        return False
    v = V-P
    if v<0:
        return True
    cnt = 0
    for ai in A[x+1:N-P+1]:
        cnt+=max(0, min(m-ai, M))
    for ai in A[:x]:
        cnt+=max(0, min(m-ai, M))
    if cnt>=M*v:
        return True
    else:
        return False
ok = N-1
ng = -1
while ok-ng>1:
    mid = (ok+ng)//2
    if C(mid):
        ok = mid
    else:
        ng = mid
print(N-ok)

Submission status: Accepted

Solution code:
from sys import stdin
def main():
    n, m, v, p = map(int, stdin.readline().split())
    a = map(int, stdin.readline().split())
    a.sort()
    s = [0] * (n + 1)
    for i, x in enumerate(a):
        s[i+1] = s[i] + x
    ans = 0
    for i in xrange(n):
        x = a[i] + m
        if x < a[-p]:
            continue
        r = v - p - i
        if r > 0:
            u = r * m
            if u <= x * (n - p - i) - s[n-p+1] + s[i+1]:
                ans += 1
        else:
            ans += 1
    print ans
main()

Submission status: Runtime Error

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()))
def judge(i):
    if len(A) <= P:
        return True
    a = A[i]
    if V <= P:
        return a+M >= A[-P]
    k = max2(0,V-P+1-i)
    if k-P >= 0:
        return False
    else:
        return a+M > A[-P+k]

i = bisect(-1,N-1,judge)
x = A[i]
while A[i-1] == x:
    i -= 1
print(N-i)

Submission status: Runtime Error

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()))
    with open('PastAGC/01-08.txt', 'r') as f:
        N, M, V, P = list(map(int, f.readline().split()))
        A = list(map(int, f.readline().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: Runtime Error

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 + 1
while right - left > 1:
    pos = (left + right) // 2
    if alst[pos] + m < alst[p - 1]:
        right = pos
        continue
    cnt = (p - 1 + n - pos) * m
    base = alst[pos] + m
    for i in range(p, pos):
        cnt += min(m, base - alst[i])
    if cnt >= m * v:
        left = pos
    else:
        right = pos
print(right)

Submission status: Runtime Error

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    N,M,V,P = LI()
    A = LI()
    A.sort()

    ans = 0
    ac = list(itertools.accumulate(A))
    bi = bisect.bisect_left(A,A[N-P+1])
    for i in range(N):
        if i >= N-P:
            ans += 1
            continue
        if M+A[i] < A[N-P]: continue
        if V <= P:
            ans += 1
            continue

        w = ((N-P-i) * (M+A[i])) - (ac[N-P] - ac[i])
        if w >= M * (V-P-i):
            ans += 1
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import numpy as np

N, M, V, P = map(int, input().split())
A = list(map(int, input().split()))
Asorted = sorted(A)[:-(P-1)]

n = len(Asorted)
start=0
end = n
Ap = A[-1]
total = V*M
while start < end -1:
  #print(start, end)
  i = (start+end-1)//2
  Ai = Asorted[i]
  limit = (Ai + M)*(n-i-1) - sum(Asorted[i+1:]) + (i+P)*M
  if limit >= total:
    end = i+1
  else:
    start = i+1
print(np.sum(np.asarray(A)>=Asorted[start]))

Submission status: Runtime Error

Solution code:
import numpy as np

N, M, V, P = map(int, input().split())
A = list(map(int, input().split()))
Asorted = sorted(A)[:-(P-1)]

n = len(Asorted)
start=0
end = n
Ap = A[-1]
th = 0
total = V*M
while start < end -1:
  i = (start+end)//2
  Ai = Asorted[i]
  limit = (Ai + M)*(n-i-1) - sum(Asorted[i+1:]) + (i+P)*M
  if limit >= total:
    end = i
    th = i
  else:
    start = i

print(np.sum(np.asarray(A)>=Asorted[th]))

Submission status: Runtime Error

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

#二分探索するからAをsortする
A = sorted(A,reverse=True)

left=0
right=N-1

while left<=right:
    mid = (left+right)//2

    if mid<P:#そもそも入っている
        left = mid + 1
    elif A[mid] + M < A[P-1]:
        right = mid - 1
    else:
        voted = P * M
        for _ in range(mid+1,N):
            voted += M

        for v in A[P-1:mid]:
            voted += min(max(A[mid]+M-v,0),M)

        if voted <=M*V:
            right = mid-1
        else:
            left= mid+1

print(low)

Submission status: Runtime Error

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

#二分探索するからAをsortする
A = sorted(A,reverse=True)

left=0
right=N

while left<=right:
    mid = (left+right)//2

    if mid<P:#そもそも入っている
        left = mid + 1
    elif A[mid] + M < A[P-1]:
        right = mid - 1
    else:
        voted = P * M
        voted += (N-mid-1)*M

        for v in A[P-1:mid]:
            voted += min(max(A[mid]+M-v,0),M)

        if voted <=M*V:
            right = mid-1
        else:
            left= mid+1

print(left)

Submission status: Runtime Error

Solution code:
def main():
    import sys 
    input= sys.stdin.readline
    n,m,v,p=map(int,input().split())
    a=list(map(int,input().split()))
    a.sort(reverse=True)
    cnt=p
    #from bisect import bisect_left
    #print(a[5]+m)
    for i in range(p,n):
        if (a[i]+m )<a[p-1]:
            break
        # 3 2 2 1 1 0
        cnt+= ((a[i]+m)*(i-p+1)-sum(a[p-1:i])+(n-(i-p+1))*m)>=v*m:
              
    print(cnt)

if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
N,M,V,P=map(int,input().split())
alist=list(map(int,input().split()))
alist.sort(reverse=True)

def isAcceptable(x):
  if x<P:
    return True
  elif alist[x]+M<alist[P-1]:
    return False
  else:
    okvote=(P-1)*M+(N-x)*M
    for i in range(P,x):
      okvote+=alist[x]+M-alist[i]
    
    if okvote<M*V:
      return False
    else:
      return True

l,r=0,N-1
while(l<=r):
  mid=(l+r)//2
  if isAcceptable(mid) and not isAcceptable(mid+1):
    break
  elif isAcceptable(mid+1):
    l=mid+1
  else:
    r=mid-1
    
print(mid+1)