๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] LCS BOJ #9251

by seolhee2750 2022. 5. 26.
๋ฌธ์ œ

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

 

9251๋ฒˆ: LCS

LCS(Longest Common Subsequence, ์ตœ์žฅ ๊ณตํ†ต ๋ถ€๋ถ„ ์ˆ˜์—ด)๋ฌธ์ œ๋Š” ๋‘ ์ˆ˜์—ด์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋ชจ๋‘์˜ ๋ถ€๋ถ„ ์ˆ˜์—ด์ด ๋˜๋Š” ์ˆ˜์—ด ์ค‘ ๊ฐ€์žฅ ๊ธด ๊ฒƒ์„ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ACAYKP์™€ CAPCAK์˜ LCS๋Š” ACAK๊ฐ€ ๋œ๋‹ค.

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
a = input()
b = input()

dp = [[0 for _ in range(len(b)+1)] for _ in range(len(a)+1)]
for i in range(1, len(a)+1):
    for j in range(1, len(b)+1):
        if a[i-1] == b[j-1]:
            dp[i][j] = dp[i-1][j-1] + 1
        else:
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

print(dp[-1][-1])

๐Ÿ‘‰ DP ๋ฌธ์ œ

2์ฐจ์› ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค์–ด์„œ ๊ฐ™์€ ๊ธ€์ž๊ฐ€ ์žˆ์„ ๋•Œ๋งˆ๋‹ค ์นด์šดํŠธ๋ฅผ ๋ˆ„์ ํ•ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ

๋น„์Šทํ•œ ์œ ํ˜•์˜ ๋ฌธ์ œ๋“ค์ด ๋งŽ์€๋ฐ,

์•„์ง ๋ณด์ž๋งˆ์ž ๋ฐ”๋กœ ํ’€์ง€๋Š” ๋ชปํ•˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

๋งŽ์ด ํ’€์–ด๋ด์•ผ๊ฒ ๋‹น

๋Œ“๊ธ€