Problem I: Longest Common Subsequence
Time Limit: 1 Sec Memory Limit: 32 MB
http://192.168.8.233/problem.php?cid=1061&pid=8
Topic description
For example: Z=<a,b,f,c> is a subsequence of the sequence X=<a,b,c,f,b,c>, the subscript sequence of elements in Z in X is <1, 2,4,6>.
Given two sequences X and Y, what is the length of their longest common subsequence?
enter
output
sample input
abcfbc abfcab
programming contest
abcd mnp
Sample output
4
2
0
Taking the strings "sadstory" and "adminsorry" as an example, the longest common subsequence (for "adsory", the length is 6.
Problem-solving idea: Let the two-dimensional array dp[i][j] represent the longest common subsequence before the i-bit of string A and the j-bit of string B, for example, dp[4][6] represents "sads " and the longest common subsequence length of "admins". Then A[i] and B[j] can be divided into 2 cases:
(1) A[i]==B[j], indicating that the length of the longest common subsequence of string A and string B has increased by 1 bit, that is, dp[i][j]=dp[i-1] [j-1]+1. For example, in the example dp[4][6] means "sads" and "admins", because A[4]==B[6], so dp[4][6]=dp[3][5] +1 is 3
(2) A[i]!=B[j], indicating that the longest common subsequence before the i-bit of string A and the j-bit of string B cannot be extended, so dp[i][j] will Inherit dp[i-1][j] and dp[i][j-1], that is, dp[i][j]=max(dp[i-1][j],dp[i][j- 1]). For example, dp[3][3] represents the length of the longest common subsequence of "sad" and "adm", but A[3]!=B[3], so dp[3][3] cannot be used in the original Therefore, it will inherit the larger value of the longest common subsequence of "sa" and "adm", "sad" and "ad", that is, the length of the longest common subsequence of "sad" and "ad" is 2. (In a sense, i,j here are equal in status)
From this, the state transition equation can be obtained:
Boundary: dp[i][0]=dp[0][j]=0 (string subscript starts at 1, subscript 0 is therefore 0)
In this way, dp[i][j] has nothing to do with the previous state, the entire dp array can be obtained from the boundary, and finally dp[n][m] is the required result
AC code:
# include <stdio.h> # include <string.h> int max(int a, int b) { if (a > b) return a; else return b; } int main(void) { int i, j, dp[101][101]; char str1[101], str2[101]; while (~ scanf("%s%s", str1+1, str2+1)) { memset(dp, 0, sizeof(dp)); for (i = 1; str1[i]; i ++) for (j = 1; str2[j]; j ++) if(str1[i] == str2[j]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i][j-1], dp[i-1][j]); printf("%d\n", dp[i-1][j-1]); } return 0; }