14888번 – 연산자끼워넣기

문제

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

풀이

코드

from itertools import permutations
from math import ceil

def divide(a, b):
  if a < 0 and b > 0:
    return -1*((a*-1)//b)
  return a//b

def answer():
  global n, nums, operations
  PLUS, MINUS, MULTIPLE, DIVIDE = (1, 2, 3, 4)
  opArr = []
  for i in range(len(operations)):
    if operations[i] > 0:
      opArr = opArr + [(i+1) for _ in range(operations[i])]
  perms = list(permutations(opArr, len(opArr)))
  results = []
  for ops in perms:
    result = nums[0]
    for i in range(len(nums)-1):
      left, right = (result, nums[i+1])
      op = ops[i]
      if op == PLUS: result = left+right
      elif op == MINUS: result = left-right
      elif op == MULTIPLE: result = left*right
      elif op == DIVIDE: result = divide(left, right)
    results.append(result)
  print(max(results))
  print(min(results))
  
n = int(input())
nums = list(map(int, input().split()))
operations = list(map(int, input().split()))
answer()

 

Leave a Reply

Your email address will not be published.