[BaekJoon] ๋ฐฑ์ค€ 9251๋ฒˆ : LCS

Updated:

9251๋ฒˆ : LCS

์ •๋ง ์–ด๋ ค์› ๋˜ ๋ฌธ์ œ์—ฌ์„œ ํ•œ์ฐธ์„ ๊ณ ๋ฏผํ•˜๋‹ค ๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด๋ฅผ ์ฐธ์กฐํ•˜์—ฌ ํ’€์—ˆ๋‹ค..

[๋ฐฑ์ค€] 9251๋ฒˆ C/C++ ํ’€์ด _ LCS

์šฐ์„  ์ด ํ‘œ๋ฅผ ์ดํ•ดํ•˜๋Š”๊ฒŒ ๊ฐ€์žฅ ์ค‘์š”ํ•˜๋‹ค.

ACAYKP CAPCAK ์˜ LCS ๋ฅผ ๊ตฌํ•˜๋Š” ๊ณผ์ •์ธ๋ฐ DP ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

image

ํ‘œ์˜ ์›์†Œ๋Š” ๊ฐ ๋ฌธ์ž์—ด๋กœ ๋งŒ๋“ค์ˆ˜ ์žˆ๋Š” LCS ์˜ ๊ธธ์ด๋ฅผ ์˜๋ฏธํ•œ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด 4ํ–‰ 4์—ด์„ ๋ณด๊ฒŒ ๋˜๋ฉด CAP ACA ์˜ LCS ๊ธธ์ด๋ฅผ ๊ฐ–๊ณ ์žˆ๋‹ค.

์ด๋ ‡๊ฒŒ ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์„ ์ชผ๊ฐœ์„œ C A ์˜ LCS ๋ถ€ํ„ฐ CAPCAK ACAYKP ์˜ LCS ๋ฅผ ๊ตฌํ•ด๊ฐ€๋ฉด ๋œ๋‹ค.

ํ‘œ๋ฅผ ์ฑ„์šฐ๋Š” ๊ทœ์น™์€ ๋‘ ๊ฐœ์˜ ๋ฌธ์ž์—ด ๋ ๊ฐ’์ด ๊ฐ™์„ ๋• ํ‘œ์˜ ์ขŒ์ƒ๋‹จ ๊ฐ’์— 1์„ ๋”ํ•˜๊ณ 

๋ฌธ์ž์—ด ๋ ๊ฐ’์ด ๋‹ค๋ฅผ ๋• ์ƒ๋‹จ๊ณผ ์™ผ์ชฝ ๊ฐ’ ์ค‘ ํฐ ๊ฐ’์„ ๋„ฃ์œผ๋ฉด ๋œ๋‹ค.

๋นจ๊ฐ„์ƒ‰ ํ˜•๊ด‘ํŽœ์ด ์น ํ•ด์ ธ ์žˆ๋Š” ๊ฒƒ์ด ๋‘ ๊ฐœ์˜ ๋ฌธ์ž์—ด ๋ ๊ฐ’์ด ๋‹ค๋ฅธ ๊ฒฝ์šฐ์ด๊ณ 

์ดˆ๋ก์ƒ‰ ํ˜•๊ด‘ํŽœ์ด ์น ํ•ด์ ธ ์žˆ๋Š” ๊ฒƒ์ด ๋‘ ๊ฐœ์˜ ๋ฌธ์ž์—ด ๋ ๊ฐ’์ด ๊ฐ’์€ ๊ฒฝ์šฐ์ด๋‹ค.

์ด๋Ÿฐ ํ’€์ด๋ฅผ ์ƒ๊ฐํ•˜๋Š” ์‚ฌ๋žŒ์€ ๋ฌธ์ œ๋ฅผ ๋งŽ์ด ํ’€์–ด์„œ ๋ณด์ด๋Š” ๊ฑธ๊นŒ.. ํƒœ์–ด๋‚  ๋•Œ ๋ถ€ํ„ฐ ๋จธ๋ฆฌ๊ฐ€ ์ข‹์•„์„œ ํ’€์ด๋ฒ•์ด ๋ฐ”๋กœ ๋ณด์ด๋Š” ๊ฑธ๊นŒ..


arr1 = input()
arr2 = input()
dp = [[0 for _ in range(len(arr1) + 1)] for _ in range(len(arr2) + 1)]

for i in range(1, len(arr2) + 1):
	for j in range(1, len(arr1) + 1):
		if arr1[j - 1] == arr2[i - 1]:
			dp[i][j] = dp[i - 1][j - 1] + 1
		else:
			dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])

print(dp[len(arr2)][len(arr1)])



Categories:

Updated:

Leave a comment