#C4247. Longest Common Subsequence Among Matrix Rows
Longest Common Subsequence Among Matrix Rows
Longest Common Subsequence Among Matrix Rows
You are given a matrix consisting of n rows of characters. Each row represents a sequence of lowercase letters. The first line of input contains two integers, ( n ) and ( m ), where ( n ) is the number of rows and ( m ) is the maximum number of characters in each row. It is possible that some rows have fewer than ( m ) characters. Your task is to find the maximum length of the longest common subsequence (LCS) between any two distinct rows of the matrix. If there is only one row, output 0.
Recall that a subsequence of a sequence is obtained by deleting some (possibly none) of the elements without changing the order of the remaining elements. The longest common subsequence of two sequences is the longest sequence which is a subsequence of both. In mathematical notation, for two sequences ( X ) and ( Y ), if their LCS has length ( L ), then
[
L = \max_{1 \leq i < j \leq n} \text{LCS}(\text{row}_i, \text{row}_j) ]
This problem requires you to compute ( L ) given the input matrix.
inputFormat
The input is read from standard input (stdin) and has the following format:
The first line contains two integers ( n ) and ( m ) separated by a space. ( n ) is the number of rows and ( m ) is the maximum number of characters in any row.
Then, ( n ) lines follow, each line containing a string of lowercase letters. Note that some strings may have fewer than ( m ) characters.
outputFormat
Output a single integer to standard output (stdout), which is the length of the longest common subsequence among any two distinct rows. If there is only one row, output 0.## sample
1 4
abcd
0