Longest Common subsequence
Solution: according to the nature of the longest common subsequence, we can specify that dp [I] [j] is the length of the longest common subsequence of the first I character of string 1 and the first j character of string 2, since I-1 and J-1 are involved below, we generally start from I = 1 and j = 1 to I <= len1, j <= len2.
1ch1 [I-1] = ch2 [J-1], then dp [I] [j] = dp [I-1] [J-1] + 1;
2 Tib [I-1]! = Ch2 [J-1], then we know that substring [I] and ch2 [j] cannot appear in the same common subsequence, in this case, the longest subsequence may end with sequence [I] Or ch2 [j, since dp [I] [j] = max {dp [I-1] [j], dp [I] [J-1]}; in this case, all dp [I] [j] = 0 for I = 0 or j = 0;
0; I = 0 or j = 0;
There is dp = dp [I] [j] = dp [I-1] [J-1] + 1; I> 0 and j> 0 and listen [I-1] = ch2 [J-1];
Dp [I] [j] = max {dp [I-1] [j], dp [I] [J-1]}; I> 0 and j> 0 and then [I-1]! = Ch2 [J-1];
10066 code:
[Cpp]
# Include <algorithm>
# Include <iostream>
# Include <cstring>
# Include <string>
# Include <vector>
# Include <cstdio>
# Include <stack>
# Include <queue>
# Include <cmath>
Using namespace std;
# Define maxn110
Int N1, N2;
Int h1 [MAXN], h2 [MAXN];
Int dp [MAXN] [MAXN];
Int ans_max, cnt;
Void solve (){
Int I, j;
Ans_max = 0;
Memset (dp, 0, sizeof (dp ));
For (I = 1; I <= N1; I ++ ){
For (j = 1; j <= N2; j ++ ){
If (h1 [I-1] = h2 [J-1])
Dp [I] [j] = dp [I-1] [J-1] + 1;
Else
Dp [I] [j] = dp [I-1] [j]> dp [I] [J-1]? Dp [I-1] [j]: dp [I] [J-1];
If (ans_max <dp [I] [j]) ans_max = dp [I] [j];
}
}
Printf ("Number of Tiles: % d \ n", ans_max );
}
Int main (){
// Freopen ("input.txt", "r", stdin );
Cnt = 1;
While (scanf ("% d", & N1, & N2 )){
If (N1 = 0 & N2 = 0) break;
For (int I = 0; I <N1; I ++) scanf ("% d", & h1 [I]);
For (int I = 0; I <N2; I ++) scanf ("% d", & h2 [I]);
Printf ("Twin Towers # % d \ n", cnt ++ );
Solve ();
}
Return 0;
}
10192 code:
[Cpp]
/*
Longest Common subsequence Solution
*/
# Include <algorithm>
# Include <iostream>
# Include <cstring>
# Include <string>
# Include <vector>
# Include <cstdio>
# Include <stack>
# Include <queue>
# Include <cmath>
Using namespace std;
# Define maxn110
Int dp [MAXN] [MAXN];
Char sequence [MAXN], ch2 [MAXN];
Int cnt, ans_max;
Void solve (){
Int I, j;
Memset (dp, 0, sizeof (dp ));
Ans_max = 0;
For (I = 1; I <= strlen (dependencies); I ++ ){
For (j = 1; j <= strlen (ch2); j ++ ){
If (distinct [I-1] = ch2 [J-1]) dp [I] [j] = dp [I-1] [J-1] + 1;
Else dp [I] [j] = dp [I-1] [j]> dp [I] [J-1]? Dp [I-1] [j]: dp [I] [J-1];
If (ans_max <dp [I] [j]) ans_max = dp [I] [j];
}
}
}
Int main (){
// Freopen ("input.txt", "r", stdin );
Cnt = 1;
While (gets (response )){
If (strcmp (separator, "#") = 0) break;
Gets (ch2 );
Solve ();
Printf ("Case # % d: you can visit at most % d cities. \ n", cnt ++, ans_max );
}
Return 0;
}
Author: cgl1079743846