자기계발
백준
1712 · 손익분기점

백준 1712번 손익분기점

문제

노트북 판매에는 대수와 상관없이 드는 고정비 A만원과, 한 대를 만들 때마다 드는 가변비 B만원이 있다. 가격이 C만원일 때 총 수입이 총 비용(고정비 + 가변비)보다 처음으로 많아지는 판매량이 손익분기점이다. A, B, C(모두 21억 이하의 자연수)가 주어지면 손익분기점을 출력하고, 존재하지 않으면 -1을 출력한다. 예를 들어 1000 70 170이면 11이다.

풀이

판매량을 q라 하면 이익 조건은 C*q > A + B*q 이다. 이를 q에 대해 풀면 q > A / (C - B) 이므로, 이 값의 정수 부분에 1을 더한 값이 처음으로 이익이 나는 판매량이 된다.

C - B가 0 이하이면 판매할수록 이익이 나지 않으므로 -1을 출력한다. 분모가 0이면 ZeroDivisionError가 나기 때문에 이 경우를 먼저 걸러 낸다. 이렇게 하면 숫자가 아무리 커도 바로 답이 나온다.

fc, vc, p = map(int, input().split())
 
def get_BEP(fc=fc, vc=vc, p=p):
    if p-vc == 0:
        return -1
    q = fc / (p-vc)
    if q > 0:
        return int(q) + 1
    else:
        return -1
 
print(get_BEP())

처음 시도한 풀이

처음에는 판매량을 1씩 늘려 가며 수입과 비용을 매번 비교했다. 반복이 최대 21억 번 가까이 돌 수 있어서 계속 시간 초과가 났다.

# 처음 고안한 로직
 
fixed_cost, variable_cost, price_per_goods = map(int, input().split())
selling_cnt = 1
 
def break_even_point(fixed_cost=fixed_cost, variable_cost=variable_cost, 
                    selling_cnt=selling_cnt, price_per_goods=price_per_goods):
 
    before_diff = 0
    while True:
        total_revenue = selling_cnt * price_per_goods
        total_cost = selling_cnt * variable_cost + fixed_cost
        if total_revenue - total_cost <= 0 and before_diff == 0:
            selling_cnt += 1
            before_diff = total_revenue - total_cost
            continue
        elif total_revenue - total_cost <= 0 and abs(before_diff) > abs(total_revenue - total_cost):
            selling_cnt += 1
            before_diff = total_revenue - total_cost
            continue
        elif total_revenue - total_cost <= 0 and abs(before_diff) <= abs(total_revenue - total_cost):
            return -1
        elif total_revenue - total_cost > 0:
            break
    
    return selling_cnt
 
print(break_even_point())

출처