๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“š Algorithm/9oormthon Challenge

[๊ตฌ๋ฆ„ํ†ค ์ฑŒ๋ฆฐ์ง€ - 9oormthon Challenge] Day 6 ๋ฌธ์ž์—ด ๋‚˜๋ˆ„๊ธฐ - Python ํŒŒ์ด์ฌ ํ’€์ด

 
๊ตฌ๋ฆ„ํ†ค ์ฑŒ๋ฆฐ์ง€ 6์ผ์ฐจ - ๋ฌธ์ž์—ด ๋‚˜๋ˆ„๊ธฐ

 

๐Ÿ“œ  ๋ฌธ์ œ 

 

 

โœ๏ธ ์ž…๋ ฅ 

 

โœ๏ธ ์ถœ๋ ฅ

 

๐Ÿ’ก ํ’€์ด 

์ง€๋‚œ์ฃผ ๋ฌธ์ œ๋“ค์— ๋น„ํ•ด ์กฐ๊ธˆ ๋‚œ์ด๋„๊ฐ€ ์žˆ์—ˆ๋˜ ๊ฒƒ ๊ฐ™๋‹ค. ๋ฌธ์ œ ๊ณต๊ฐœ ๋‹น์ผ๊นŒ์ง€ ํ’€์ง€๋Š” ๋ชปํ•˜๊ณ  ๋‹ค์Œ๋‚  ์˜ค์ „์— ํ’€๊ฒŒ๋˜์—ˆ๋‹ค. 

๋ฌธ์ž์—ด์„ ๊ฐ€๋Šฅํ•œ ์กฐํ•ฉ์œผ๋กœ ๋‚˜๋ˆ„๊ณ , ๊ทธ ์กฐํ•ฉ๋“ค์—์„œ ์ตœ๋Œ€๋ฅผ ์ฐพ์•„์•ผํ•œ๋‹ค.

๋‚˜๋Š” ๋ฌธ์ž์—ด์„ ๊ฐ€๋Šฅํ•œ ์กฐํ•ฉ์œผ๋กœ ๋‚˜๋ˆ„๋Š” ํ•จ์ˆ˜ search๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค. ์ธ์ž๊ฐ’์œผ๋กœ ๋“ค์–ด์˜ค๋Š” start๋Š” ๋ฌธ์ž์—ด ์กฐํ•ฉ์˜ ์‹œ์ž‘์„ ๋œปํ•˜๊ณ  cnt๋Š” ๋‚จ์€ ๋ฌธ์ž์—ด์„ ๋ช‡ ๋ถ€๋ถ„์œผ๋กœ ๋‚˜๋ˆŒ ๊ฒƒ์ธ์ง€๋ฅผ ๋„˜๊ฒจ์ฃผ๋„๋ก ํ–ˆ๋‹ค. global ๋ณ€์ˆ˜ set์„ ์‚ฌ์šฉํ•ด์„œ ์ €์žฅํ•˜๊ณ  ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๋„๋ก ํ–ˆ๋‹ค.  

cal ํ•จ์ˆ˜์—์„œ๋Š” ๋ฌธ์ž์—ด ์กฐํ•ฉ๋“ค์—์„œ ์ตœ๋Œ€๊ฐ’์„ ๊ณ„์‚ฐํ•˜๋„๋ก ํ–ˆ๋‹ค. start์™€ cnt๋Š” search ํ•จ์ˆ˜์™€ ๋˜‘๊ฐ™๊ณ , P๋Š” ๋ฌธ์ž์—ด์„ ์ž„์‹œ๋กœ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด์ด๋‹ค. 

์ดํ›„ main ์—์„œ๋Š” ๋ฌธ์ž์—ด์„ ์ž…๋ ฅ ๋ฐ›๊ณ  ํ•จ์ˆ˜๋“ค์„ ํ˜ธ์ถœํ•ด ๋‚˜๋ˆ„๋ฉฐ map์„ ์ƒ์„ฑํ•ด์„œ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ํ›„ ์ˆœ์„œ๋Œ€๋กœ ์ธ๋ฑ์Šค๋ฅผ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค. 

 

 

def search(start, cnt):
    global set  
    if cnt == 0:
        set.add(s[start:])
        return
    for i in range(start + 1, n - cnt + 1):
        set.add(s[start:i])
        search(i, cnt - 1)

def cal(start, cnt):
    global result
    if cnt == 0:
        result = max(result, map[s[start:]] + map[P[1]] + map[P[2]])
        return
    for i in range(start + 1, n - cnt + 1):
        P[cnt] = s[start:i]
        cal(i, cnt - 1)

n = int(input())
s = input().strip()
set = set()
P = [''] * 3
result = -1
map = {}
search(0, 2)
index = 1
for string in sorted(set):
    map[string] = index
    index += 1
cal(0, 2)
print(result)

 

 

 

728x90