File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
minjeong/DynamicProgramming Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change 1+ import sys
2+ input = sys .stdin .readline
3+
4+
5+ def min_ops_to_pal (s ):
6+ """
7+ s: list of chars
8+ return: 최소 편집 연산(삽입, 삭제, 교체만 허용)으로 s를 팰린드롬으로 만드는 비용
9+ """
10+ n = len (s )
11+ # dp[i][j]: s[i..j]를 팰린드롬으로 만드는 최소 연산 횟수
12+ dp = [[0 ] * n for _ in range (n )]
13+ # 길이 2부터 n까지 늘려가며
14+ for length in range (2 , n + 1 ):
15+ for i in range (n - length + 1 ):
16+ j = i + length - 1
17+ if s [i ] == s [j ]:
18+ dp [i ][j ] = dp [i + 1 ][j - 1 ]
19+ else :
20+ # 교체(대칭 맞추기), 삭제(왼쪽), 삭제(오른쪽)
21+ dp [i ][j ] = min (
22+ dp [i + 1 ][j - 1 ] + 1 ,
23+ dp [i + 1 ][j ] + 1 ,
24+ dp [i ][j - 1 ] + 1
25+ )
26+ for d in dp :
27+ print (d )
28+
29+ return dp [0 ][n - 1 ] if n > 0 else 0
30+
31+
32+ s = list (input ().rstrip ())
33+ n = len (s )
34+
35+ # 1. 교환 없이 삽입/삭제/교체만 사용했을 때
36+ ans = min_ops_to_pal (s )
37+ if ans <= 1 :
38+ print (ans )
39+ exit ()
40+
41+ # 2. 서로 다른 문자끼리 한 번만 교환을 허용해봤을 때, 교환 비용 1을 더해보고 개선되는지 확인
42+ for i in range (n ):
43+ for j in range (i + 1 , n ):
44+ if s [i ] != s [j ]:
45+ # 문자가 같지 않은 경우, SWAP
46+ s [i ], s [j ] = s [j ], s [i ]
47+ swap_cost = min_ops_to_pal (s ) + 1 # swap 비용 포함
48+ if swap_cost < ans : # swap한 경우가 더 작다면 ans에 업데이트
49+ ans = swap_cost
50+ # 복구
51+ s [i ], s [j ] = s [j ], s [i ]
52+ print (ans )
You can’t perform that action at this time.
0 commit comments