⚡️algorithm

[이분탐색] 백준 2512. 예산

남남이루 2022. 5. 13. 16:01

https://www.acmicpc.net/problem/2512
예산의 기준상한액을 출력해라.

틀렸는데, 왜 틀렸는 지 모르겠다.


상한액이 e값으로 결정된다.
예시로는 맞는데, ans 할당하는 부분이 틀렸었다.

틀린 코드

from re import S
import sys
from collections import Counter
sys.stdin = open('C:\\tech\\backjoon\\binary\\input.txt','r')
input = sys.stdin.readline

n = int(input())
arr = Counter(map(int, input().split()))
limit = int(input())
# 상한액을 출력하라 ans


def getMoney(m):
    t = 0
    for i in arr:
        t += (i if i<=m else m)
    print(t)
    return t

s = 0
e = max(arr)
while s < e:
    mid = (s+e)//2
    tot = getMoney(mid)
    print(s,e,mid, end=' /')
    if tot > limit:
        e = mid-1
        print(e,'s')

    else:
        s = mid+1
        ans = mid
        print(ans,'ans')

print(ans+1)

최종

from re import S
import sys
from collections import Counter
sys.stdin = open('C:\\tech\\backjoon\\binary\\input.txt','r')
input = sys.stdin.readline

n = int(input())
arr = Counter(map(int, input().split()))
limit = int(input())
# 상한액을 출력하라 ans


def getMoney(m):
    t = 0
    for i in arr:
        t += (i if i<=m else m)
    return t

s = 0
e = max(arr)
ans = 0
while s <= e:
    mid = (s+e)//2
    tot = getMoney(mid)
    # print(s,e,mid, end=' /')

    if tot > limit:
        e = mid-1
        # print(ans,'ans')

    else:
        s = mid+1
        # print(s,'s')

print(e)