[BOJ][๐ŸŸก5][๋ฐฑ์ค€#09251] LCS

์ž‘์„ฑ:    

์—…๋ฐ์ดํŠธ:

์นดํ…Œ๊ณ ๋ฆฌ:

ํƒœ๊ทธ: , , ,

๋ฌธ์ œ ์ถœ์ฒ˜

BAEKJOON Online Judge #9251


๋ฌธ์ œ

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


์ž…๋ ฅ

์ฒซ์งธ ์ค„๊ณผ ๋‘˜์งธ ์ค„์— ๋‘ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ๋ฌธ์ž์—ด์€ ์•ŒํŒŒ๋ฒณ ๋Œ€๋ฌธ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ์ตœ๋Œ€ 1000๊ธ€์ž๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.


์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ๋‘ ๋ฌธ์ž์—ด์˜ LCS์˜ ๊ธธ์ด๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.


์˜ˆ์ œ

์ž…๋ ฅ

ACAYKP
CAPCAK


์ถœ๋ ฅ

4


My Sol

A, B = input(), input()
al, bl = len(A), len(B)

mat = [[0]*(bl+1) for _ in range(al+1)]
for i in range(1, al+1):
    a = A[i-1]
    for j in range(1, bl+1):
        b = B[j-1]
        mat[i][j] = max(mat[i][j-1], mat[i-1][j])
        if a == b:
            mat[i][j] = max(mat[i-1][j-1]+1, mat[i][j])

print(mat[al][bl])

LCS์˜ ๊ทœ์น™๋Œ€๋กœ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด ๋œ๋‹ค. ์ด์ „์—์„œ ๋‚˜์˜จ ๊ฒƒ ์ค‘ ์ตœ๋Œ€ ์ค‘์ฒฉ์˜ ์ˆ˜๋ฅผ ์˜ฎ๊ฒจ์™€์„œ ์ด๋ฒˆ ์ฐจ๋ก€์—์„œ ๋˜ ์ค‘์ฒฉ์ด ๋œ๋‹ค๋ฉด ํ•˜๋‚˜๋ฅผ ์˜ฌ๋ ค ๊ธฐ๋กํ•ด์ค€๋‹ค. ์ด๊ฒƒ์ด ์ดํ›„์˜ ๋ˆ„์ ์œผ๋กœ ์‚ฌ์šฉ๋œ๋‹ค.


๊ฒฐ๊ณผ

๋งž์•˜์Šต๋‹ˆ๋‹ค!!


๋ชจ๋ฒ”๋‹ต์•ˆ

์ถœ์ฒ˜

word1, word2 = input(),input()
l1, l2 = len(word1), len(word2)
cache = [0] * l2

for i in range(l1):
    cnt = 0
    for j in range(l2):
        if cnt < cache[j]:
            cnt = cache[j]
        elif word1[i] == word2[j]:
            cache[j] = cnt + 1
print(max(cache))

์—ฐ์‚ฐ์‹œ๊ฐ„์ด 5๋ฐฐ๋‚˜ ์งง์€๋ฐ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰๊ณผ ์ฝ”๋“œ๋Ÿ‰๋„ ์งง์€ ์ฝ”๋“œ๊ฐ€ ์žˆ์–ด์„œ ๋ถ„์„ํ•ด๋ณด๋ ค ํ•œ๋‹ค.

cache๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ‘ธ๋Š” ๊ฒƒ ๊ฐ™์€๋ฐ 2์ค‘ for๋ฌธ๋„ ๋Œ๋ฆฌ๊ณ โ€ฆ ์–ด๋–ค ๋ฐฉ์‹์œผ๋กœ ํ‘ผ ๊ฑด์ง€๋Š” ์ž˜ ๋ชจ๋ฅด๊ฒ ๋‹ค.

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ