본문 바로가기
알고리즘 문제풀이/백준

백준 14888

by Hoseok 2023. 5. 23.
728x90
반응형

 

 

 

코드

import sys
from itertools import permutations

def calculate(operands, operators):
    result = operands[0]
    for i in range(1, len(operands)):
        if operators[i-1] == '+':
            result += operands[i]
        elif operators[i-1] == '-':
            result -= operands[i]
        elif operators[i-1] == '*':
            result *= operands[i]
        elif operators[i-1] == '/':
            if result < 0:
                result = -((-result) // operands[i])
            else:
                result //= operands[i]
    return result

def generate_operators(operator_counts):
    operators = []
    for i, count in enumerate(operator_counts):
        if i == 0:
            operators += ['+'] * count
        elif i == 1:
            operators += ['-'] * count
        elif i == 2:
            operators += ['*'] * count
        elif i == 3:
            operators += ['/'] * count
    return operators

def solution(N, operands, operators):
    max_result = -sys.maxsize - 1  # 최댓값 초기화
    min_result = sys.maxsize  # 최솟값 초기화

    # 가능한 모든 연산자 순열 생성
    operator_permutations = list(set(permutations(operators, N-1)))

    # 모든 연산자 순열에 대해 결과 계산
    for perm in operator_permutations:
        result = calculate(operands, perm)
        max_result = max(max_result, result)
        min_result = min(min_result, result)

    return max_result, min_result

# 입력 처리
N = int(input())
operands = list(map(int, input().split()))
operator_counts = list(map(int, input().split()))

operators = generate_operators(operator_counts)

# 문제 해결 및 결과 출력
max_result, min_result = solution(N, operands, operators)
print(max_result)
print(min_result)
728x90
반응형

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

백준 2193  (0) 2023.05.23
백준 14888 #2  (0) 2023.05.23
백준 2468  (0) 2023.05.22
백준 2667 #2  (0) 2023.05.17
백준 2798 #2  (0) 2023.05.17