출처 : 백준 #1958
시간 제한 | 메모리 제한 |
---|---|
2초 | 128MB |
첫 줄에는 첫 번째 문자열이, 둘째 줄에는 두 번째 문자열이, 셋째 줄에는 세 번째 문자열이 주어진다. 각 문자열은 알파벳 소문자로 이루어져 있고, 길이는 100보다 작거나 같다.
첫 줄에 첫 번째 문자열과 두 번째 문자열과 세 번째 문자열의 LCS의 길이를 출력한다.
abcdefghijklmn
bdefg
efg
3
ABCBDAB
, BDCABA
BDAB
, BCBA
가 존재한다.# 백준 1958번 LCS3 (문자열)
import sys
from heapq import heappop, heappush
input = sys.stdin.readline
x = "%"+input().rstrip()
y = "%"+input().rstrip()
z = "%"+input().rstrip()
temp = []
heappush(temp, (len(x), x))
heappush(temp, (len(y), y))
heappush(temp, (len(z), z))
len1, str1 = heappop(temp)
len2, str2 = heappop(temp)
len3, str3 = heappop(temp)
C = [([0] * len1) for _ in range(len2)]
result = "%"
for i in range(len2):
for j in range(len1):
if i == 0 or j == 0:
C[i][j] = 0
elif str1[j] == str2[i]:
C[i][j] = C[i-1][j-1] + 1
result += str1[j]
else:
C[i][j] = max(C[i][j-1], C[i-1][j])
print(result)
S = [0] * len(result)
for i in range(1, len3):
for j in range(len(result)):
if j == 0:
S[j] = 0
elif str3[i] == result[j]:
S[j] += 1
else:
S[j] = max(S[j], S[j-1])
print(S[-1])
# 백준 1958번 LCS3 (문자열)
import sys
from heapq import heappop, heappush
input = sys.stdin.readline
x = "%"+input().rstrip()
y = "%"+input().rstrip()
z = "%"+input().rstrip()
temp = []
heappush(temp, (len(x), x))
heappush(temp, (len(y), y))
heappush(temp, (len(z), z))
len1, str1 = heappop(temp)
len2, str2 = heappop(temp)
len3, str3 = heappop(temp)
C = [[([0] * len1) for _ in range(len2)] for _ in range(len3)]
for k in range(len3):
for i in range(len2):
for j in range(len1):
if i == 0 or j == 0 or k == 0:
C[k][i][j] = 0
elif str1[j] == str2[i] and str2[i] == str3[k]:
C[k][i][j] = C[k-1][i-1][j-1] + 1
else:
C[k][i][j] = max(C[k-1][i][j], C[k][i-1][j], C[k][i][j-1])
print(C[len3-1][len2-1][len1-1])