[BaekJoon] 9252๋ฒˆ : LCS 2

Updated:

9252๋ฒˆ : LCS 2


[BaekJoon] ๋ฐฑ์ค€ 9251๋ฒˆ : LCS ์˜ ๋‘ ๋ฒˆ์งธ ๋ฌธ์ œ์ด๋‹ค.

9251๋ฒˆ์€ LCS ์˜ ๊ธธ์ด๋งŒ ๊ตฌํ•˜๋ฉด ๋์ง€๋งŒ ์ด ๋ฌธ์ œ๋Š” ๊ธธ์ด์™€ ํ•จ๊ป˜ LCS ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.

๊ธธ์ด๋งŒ ๊ตฌํ• ๋•Œ๋Š” ๋ฌธ์ž์—ด ๊ธธ์ด๋งŒ ๊ฐ€์ง€๊ณ  dp ๋ฅผ ํ–ˆ๋‹ค๋ฉด ์ด๋ฒˆ์—๋Š” ๊ธธ์ด ๋Œ€์‹  ๋ฌธ์ž์—ด ์ž์ฒด๋ฅผ ๊ฐ€์ง€๊ณ  dp ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋ฉด ๋œ๋‹ค.

์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๋น„๊ตํ•˜๋Š” ๋ฌธ์ž๊ฐ€ ๋‹ค๋ฅด๋ฉด ํ˜„์žฌ ์œ„์น˜์—์„œ ์™ผ์ชฝ, ์œ„์ชฝ ์ค‘ ๊ธด ๋ฌธ์ž์—ด์„ ๊ทธ๋Œ€๋กœ ๊ฐ€์ ธ์˜ค๊ณ 

๋ฌธ์ž๊ฐ€ ๊ฐ™๋‹ค๋ฉด ์™ผ์ชฝ ์œ„ ๋Œ€๊ฐ์„  ์œ„์น˜์˜ ๋ฌธ์ž์—ด๊ณผ ํ˜„์žฌ ๋ฌธ์ž์—ด์„ ๋”ํ•œ๋‹ค.

ํ–‰๋ ฌ๋กœ ๊ทธ๋ ค์„œ ํ‘œํ˜„ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

image


def solution():
	len_fisrt = len(first)
	len_second = len(second)
	dp = [[''] * (len_fisrt + 1) for _ in range(len_second + 1)]

	for i in range(1, len_second + 1):
		for j in range(1, len_fisrt + 1):
			if second[i - 1] == first[j - 1]:
				dp[i][j] = dp[i - 1][j - 1] + second[i - 1]
			else:
				if len(dp[i - 1][j]) < len(dp[i][j - 1]):
					dp[i][j] = dp[i][j - 1]
				else:
					dp[i][j] = dp[i - 1][j]

	print(len(dp[len_second][len_fisrt]))
	print(dp[len_second][len_fisrt])
	return


if __name__ == '__main__':
	first = input()
	second = input()

	solution()



Categories:

Updated:

Leave a comment