์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ/BOJ_Python

[BOJ/Step14] 14888 : ์—ฐ์‚ฐ์ž ๋ผ์›Œ๋„ฃ๊ธฐ (Python)

NaNaRin๐Ÿ™ƒ 2021. 2. 22. 17:35

www.acmicpc.net/problem/14888

 

14888๋ฒˆ: ์—ฐ์‚ฐ์ž ๋ผ์›Œ๋„ฃ๊ธฐ

์ฒซ์งธ ์ค„์— ์ˆ˜์˜ ๊ฐœ์ˆ˜ N(2 ≤ N ≤ 11)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” A1, A2, ..., AN์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ Ai ≤ 100) ์…‹์งธ ์ค„์—๋Š” ํ•ฉ์ด N-1์ธ 4๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ, ์ฐจ๋ก€๋Œ€๋กœ ๋ง์…ˆ(+)์˜ ๊ฐœ์ˆ˜, ๋บ„์…ˆ(-)์˜ ๊ฐœ์ˆ˜, 

www.acmicpc.net


์ž…๋ ฅ๋ฐ›์€ ์—ฐ์‚ฐ์ž ๊ฐœ์ˆ˜๋ฅผ ์–ด๋–ป๊ฒŒ ๋ฐฐ์น˜ํ•˜๋Š๋ƒ๊ฐ€ ๊ด€๊ฑด..

์ผ๋‹จ ์ˆœ์—ด์„ ๋ชจ๋‘ ๊ตฌํ•œ ๋‹ค์Œ์— ์ง‘ํ•ฉ์œผ๋กœ ๋ณ€๊ฒฝํ•ด ์ค‘๋ณต์„ ๋‚ ๋ ค๋ฒ„๋ฆฌ๊ธฐ๋กœ ํ–ˆ๋‹ค

์ฒ˜์Œ์—๋Š” ์ˆซ์ž + ์—ฐ์‚ฐ์ž + ์ˆซ์ž ํ•ด์„œ ์ญ‰ str๋กœ ๋งŒ๋“ค์–ด eval ํ•จ์ˆ˜๋กœ ๊ณ„์‚ฐํ–ˆ๋Š”๋ฐ

์Œ์ˆ˜ // ์–‘์ˆ˜ ํ•˜๋ฉด ๊ฐ’์ด ๋‹ฌ๋ผ์ง€๋Š”๊ฒƒ... ๊ทธ๋ž˜์„œ ์–ด์ฉ”์ˆ˜ ์—†์ด ํ•˜๋‚˜ํ•˜๋‚˜ ๊ณ„์‚ฐํ–ˆ๋‹ค

 

์—ฐ์‚ฐ์ž์™€ ์ˆซ์ž ๋ฆฌ์ŠคํŠธ๋ฅผ ์ „๋‹ฌํ•˜๋ฉด ๊ณ„์‚ฐํ•ด์„œ ๊ฒฐ๊ณผ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ expr

  1. num์˜ ์ธ๋ฑ์Šค idx = 0

  2. ๊ณ„์‚ฐํ•œ ๊ฒฐ๊ณผ๊ฐ’์„ ์ €์žฅํ•  total ์€ ์ฒซ๋ฒˆ์งธ ์ˆซ์ž๋กœ ์ดˆ๊ธฐํ™”

  3. ์—ฐ์‚ฐ์ž ๋ฆฌ์ŠคํŠธ ope์—์„œ ํ•˜๋‚˜์”ฉ ๊ฐ€์ ธ์˜จ๋‹ค

    3-1. ์—ฐ์‚ฐ์ž๊ฐ€ +, -, * ์ผ ๋•Œ๋Š” ๊ทธ๋Œ€๋กœ ๊ณ„์‚ฐ

    3-2. ์—ฐ์‚ฐ์ž๊ฐ€ / ์ผ ๋•Œ๋Š” ์ฒซ๋ฒˆ์งธ ํ”ผ์—ฐ์‚ฐ์ž = total ์ด ์Œ์ˆ˜์ธ์ง€ ํ™•์ธํ•ด์„œ ๋”ฐ๋กœ ๊ณ„์‚ฐํ•ด์ค€๋‹ค (์–‘์ˆ˜๋กœ ๋ฐ”๊พผ ๋’ค ๋ชซ์„ ์ทจํ•˜๊ณ , ๊ทธ ๋ชซ์„ ์Œ์ˆ˜๋กœ ๋ฐ”๊พผ ๊ฒƒ)

  4. ๊ฒฐ๊ณผ๊ฐ’ ๋ฐ˜ํ™˜

 

1. ์ˆซ์ž์™€ ์—ฐ์‚ฐ์ž ๊ฐœ์ˆ˜๋ฅผ ๊ฐ๊ฐ nums, op1 ๋ฆฌ์ŠคํŠธ์— ์ €์žฅํ•œ๋‹ค

2. ์—ฐ์‚ฐ์ž ๊ฐœ์ˆ˜์— ๊ฐ๊ฐ +, -, *, / ๋ฅผ ๊ณฑํ•ด ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด op2๋กœ ๋งŒ๋“ ๋‹ค

3. itertools ๋ชจ๋“ˆ์˜ permutation() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด op2๋ฅผ ์‚ฌ์šฉํ•ด ์ˆœ์—ด ์กฐํ•ฉ์„ ์ƒ์„ฑํ•ด ์ง‘ํ•ฉ operator์œผ๋กœ ์ €์žฅํ•œ๋‹ค ( ์ค‘๋ณต ์ œ๊ฑฐ )

4. ์ง‘ํ•ฉ operator์„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ณ€๊ฒฝํ•œ๋‹ค

5. operator์˜ ์š”์†Œ๋ฅผ ๊ฐ๊ฐ ๊ณ„์‚ฐํ•˜์—ฌ ๊ฒฐ๊ณผ๊ฐ’์„ ์ €์žฅํ•˜๋Š” ๋ฆฌ์ŠคํŠธ result์— ์ถ”๊ฐ€

6. result์˜ ์ตœ๋Œ“๊ฐ’๊ณผ ์ตœ์†Ÿ๊ฐ’ ์ถœ๋ ฅ

 

# 14888.py

import itertools


def expr(ope, num):
    idx = 0
    total = num[idx]
    for i in ope:
        if i == '+':
            total = total + num[idx+1]
        elif i == '-':
            total = total - num[idx+1]
        elif i == '*':
            total = total * num[idx+1]
        elif i == '/':
            if total < 0:
                total = (abs(total) // num[idx+1]) * -1
            else:
                total = total // num[idx+1]
        idx += 1
    return total


n = int(input())
nums = list(map(int, input().split()))
op1 = list(map(int, input().split()))

op2 = '+' * op1[0] + '-' * op1[1] + '*' * op1[2] + '/' * op1[3]
operator = set(itertools.permutations(op2, n - 1))
operator = list(operator)
operator.sort()

result = []
for i in operator:
    result.append(expr(i, nums))

print(max(result))
print(min(result))