일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- DateTime
- 그리디
- Set
- 자바
- 정규식
- BFS
- divmod
- dfs
- 프로그래머스
- backjoon
- 카카오
- 추석맞이 코딩챌린지
- 파이썬
- heapq
- lambda
- 백준
- KAKAO BLIND RECRUITMENT
- java
- python
- Zip
- 다익스트라
- Re
- 이분탐색
- 동적 계획법
- Combinations
- 재귀함수
- 수학
- programmers
- 위클리 챌린지
- 정렬
Archives
- Today
- Total
상상쓰
[백준] 괄호 추가하기 본문
https://www.acmicpc.net/problem/16637
16637번: 괄호 추가하기
길이가 N인 수식이 있다. 수식은 0보다 크거나 같고, 9보다 작거나 같은 정수와 연산자(+, -, ×)로 이루어져 있다. 연산자 우선순위는 모두 동일하기 때문에, 수식을 계산할 때는 왼쪽에서부터 순
www.acmicpc.net
DFS 알고리즘, 재귀함수를 이용하여 괄호를 추가할 수 있는 모든 경우를 나타내었다.
3+8*7-9*2 를 예로 들었을 때, rf 함수에 str(l) + o + l_ + o_ + r_ 를 출력해보면
0+(3+8)*7-9*2
0+(3+8)*(7-9)*2
0+(3+8)*7-(9*2)
0+3+(8*7)-9*2
0+3+(8*7)-(9*2)
0+3+8*(7-9)*2
0+3+8*7-(9*2)
(0+ 는 편의상 만들어준 식이다.)
이를 priority 함수를 만들어 곱셈이 우선순위인 기본적인 사칙연산과 달리 왼쪽을 우선으로 계산하여 그 중 최댓값을 answer 로 한다.
import sys
answer = float('-inf')
def rf(l, o, r):
global answer
for i in range(len(r) // 2):
l_ = r[:2*i] + '(' + r[2*i:2*i+3] + ')'
if len(r) >= 2*i+4:
o_ = r[2*i+3]
r_ = r[2*i+4:]
else:
o_ = ''
r_ = ''
temp = priority(str(l) + o + l_ + o_ + r_)
if answer < temp:
answer = temp
rf(str(l)+o+l_, o_, r_)
def priority(s):
operation = ['+', '*', '-']
temp = ''
chk = 0
for i in s:
if i == '(':
chk += 1
else:
if i == ')':
chk -= 1
if chk == 0 and i in operation:
temp = str(eval(temp)) + i
else:
temp += i
return eval(temp)
def solution(N, S):
global answer
if N == 1:
answer = S
else:
rf('0', '+', S)
print(answer)
N = int(sys.stdin.readline())
S = sys.stdin.readline().strip()
solution(N, S)
'Coding Test' 카테고리의 다른 글
[백준] 터렛 (0) | 2021.08.17 |
---|---|
[프로그래머스] 쿠키 구입 (0) | 2021.08.15 |
[프로그래머스] 최고의 집합 (0) | 2021.08.13 |
[프로그래머스] 블록 게임 (0) | 2021.08.12 |
[백준] 돌 게임 (0) | 2021.08.12 |
Comments