BOJ - 9735 - 삼차 방정식 풀기

Updated:

import sys
from decimal import *

def solution():
    N = int(sys.stdin.readline())
    for i in range(N):
        ret = []
        a, b, c, d = map(int, sys.stdin.readline().split())
    
        for j in range(-1000000, 1000001):
            if a * j * j * j + b * j * j + c * j + d == 0:
                ret.append(Decimal(j))
                break
                
        b = a * ret[0] + b
        c = b * ret[0] + c
    
        if b * b - 4 * a * c < 0:
            print(ret[0])
        elif b * b - 4 * a * c == 0:
            ret.append(Decimal(-b / (2 * a)))
            ret.sort()
            if ret[0] == ret[1]:
                print(ret[0])
            else:
                print(ret[0], ret[1])
        elif b * b - 4 * a * c > 0:
            ret.append(Decimal(-b + (b * b - 4 * a * c) ** Decimal(0.5)) / (2 * a))
            ret.append(Decimal(-b - (b * b - 4 * a * c) ** Decimal(0.5)) / (2 * a))
            ret.sort()
            if ret[0] == ret[1]:
                print(ret[0], ret[2])
            elif ret[1] == ret[2]:
                print(ret[0], ret[1])
            else:
                print(ret[0], ret[1], ret[2])
solution()

https://www.acmicpc.net/problem/9735

Categories:

Updated:

Leave a comment