[BOJ][๐ŸŸก4][๋ฐฑ์ค€#09252] LCS 2

์ž‘์„ฑ:    

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

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

ํƒœ๊ทธ: , , ,

๋ฌธ์ œ ์ถœ์ฒ˜

BAEKJOON Online Judge #9252


๋ฌธ์ œ

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


์ž…๋ ฅ

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


์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ๋‘ ๋ฌธ์ž์—ด์˜ LCS์˜ ๊ธธ์ด๋ฅผ, ๋‘˜์งธ ์ค„์— LCS๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. LCS๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐ€์ง€์ธ ๊ฒฝ์šฐ์—๋Š” ์•„๋ฌด๊ฑฐ๋‚˜ ์ถœ๋ ฅํ•˜๊ณ , LCS์˜ ๊ธธ์ด๊ฐ€ 0์ธ ๊ฒฝ์šฐ์—๋Š” ๋‘˜์งธ ์ค„์„ ์ถœ๋ ฅํ•˜์ง€ ์•Š๋Š”๋‹ค.


์˜ˆ์ œ

์ž…๋ ฅ

ACAYKP
CAPCAK


์ถœ๋ ฅ

4
ACAK


My Sol

A = input()
B = input()
al, bl = len(A), len(B)
LCS = [[[0, ''] for _ in range(bl+1)] for _ in range(al+1)]

for i in range(1, al+1):
    for j in range(1, bl+1):
        LCS[i][j] = sorted([LCS[i][j-1], LCS[i-1][j]], key=lambda x:-x[0])[0]
        if A[i-1] == B[j-1]:
            n, txt = LCS[i-1][j-1]
            if n >= LCS[i][j][0]:
                LCS[i][j] = [n+1, txt+A[i-1]]

ret = LCS[al][bl]
if ret[0]:
    for a in ret:
        print(a)
else:
    print(0)

LCS๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” DP๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.

  1. ๋‘ ํ…์ŠคํŠธ๋ฅผ ๊ฐ๊ฐ A, B๋กœ ๋‘๊ณ  ์ด ๊ธธ์ด๋ฅผ al, bl๋กœ ๊ณ„์‚ฐํ•˜์˜€๋‹ค.
  2. ์ด al๊ณผ bl์„ ๊ฐ๊ฐ ํ–‰๊ณผ ์—ด๋กœ ๋‘๋Š” 2์ฐจ์› ๋ฐฐ์—ด LCS๋ฅผ ๋งŒ๋“ค๊ณ , ๊ฐ ์นธ์„ ์ตœ์ดˆ ๊ธธ์ด์ธ 0๊ณผ ๋นˆ ๊ฐ’์„ ๊ฐ€์ง„ ๋ฐฐ์—ด๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.
  3. ๊ฐ ํ–‰๊ณผ ์—ด์„ ๋Œ๋ฉฐ A์™€ B์˜ ํ•œ ์•ŒํŒŒ๋ฒณ์ด ๊ฐ™๊ณ , ์ง์ „๊นŒ์ง€ ๊ฐ€๋Šฅํ•œ ์ตœ๋Œ€๊ณตํ†ต๋ถ€๋ถ„์˜ ๊ธธ์ด๊ฐ€ ํ˜„์žฌ ์นธ์˜ ๊ณตํ†ต ๋ถ€๋ถ„์˜ ๊ธธ์ด๋ณด๋‹ค ๊ฐ™๊ฑฐ๋‚˜ ํฌ๋‹ค๋ฉด ์ด๋ฒˆ LCS์นธ์„ (i-1, j-1)์— ์•ŒํŒŒ๋ฒณ์„ ํ•˜๋‚˜ ๋ถ™์ธ ๊ฒƒ์œผ๋กœ ๊ฐ„์ฃผํ•œ๋‹ค.
  4. LCS[i][j-1]์™€ LCS[i-1][j] ์ค‘ ๊ธธ์ด๊ฐ€ ๋” ๊ธด ๊ฒƒ์„ ๊ฐ ์นธ์˜ ์™„์ „ํƒ์ƒ‰์—์„œ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.
  5. LCS[al][bl]์ด ๊ฒฐ๊ณผ์ด๊ณ , ์ด ๊ฐ’์ด 0์ด๋ผ๋ฉด 0๋งŒ, ์•„๋‹ˆ๋ผ๋ฉด ๊ธธ์ด์™€ ํ…์ŠคํŠธ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.


๊ฒฐ๊ณผ

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

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