This topic was written completely in Char, and now trying to write with a string, it feels good, the idea is as follows:
We use AX to represent the subsequence of sequence A's successive first x items, namely ax= a1,a2,...... ax, by= b1,b2,...... by, we use LCS (x, y) to denote their longest common subsequence length, which is equivalent to finding LCS (M,n). For convenience we use L (x, y) to represent one of the longest common sub-sequences of ax and by.
Let's look at how to ask for LCS (x, y). We make x indicate that the sub-sequence considers the last item
(1) Ax = by
Then the last item of their L (Ax, by) must be this element.
Why is it. For convenience, we make t = Ax = by, we use contradiction: Suppose that the last item of L (x, y) is not T,
Either L (x, y) is an empty sequence (don't forget this), or the last item of L (x, y) is aa=bb≠t, and obviously a < X, b < Y. In either case, we can take the T to the back of this L (x, y) and get a longer common subsequence. Contradiction.
If we remove the last ax from the sequence ax to get Ax-1, the last item is also deleted from the sequence by to get By-1, (say a corner labeled 0 o'clock, that the subsequence is an empty sequence), then we delete the last item from L (x, y) and the resulting sequence is L (x–1, y-1). Why is it. The same as above, if the resulting sequence is not L (x-1, y-1), then it must be shorter than L (x-1, y-1) (note l (,) is a set. ), then it is followed by an element t to get the subsequence L (x, y) also than L (X-1, y-1) connected to the element T to get the sub-sequence short, which with L (x, y) is the longest common sub-sequence contradiction.
So L (x, y) = L (x-1, y-1) is finally connected to the element t
LCS (Ax, by) = LCS (X-1, y-1) + 1
This problem is not a good place to write the path of the block, we want a character array inverted record, and then inverted output
#include <iostream> #include <stdio.h> #include <string.h> using namespace std;
int dp[1005][1005];
Char s[1005];
String A, B;
int main () {while (cin>>a>>b) {memset (dp,0,sizeof (DP));
Memset (s,0,sizeof (s));
int P=a.length ();
int Q=b.length ();
for (int i=1;i<=a.length (), i++) for (int j=1;j<=b.length (); j + +) {if (a[i-1]==b[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else Dp[i][j]=max (dp[i-1][j],dp[i][j-1]);
} int k=0;
while (Dp[p][q]) {if (dp[p][q]==dp[p-1][q]) p--;
else if (Dp[p][q]==dp[p][q-1]) {q--;
} else if (Dp[p][q]!=dp[p-1][q-1]) {s[k++]=a[p-1];
p--;
q--;
}} for (int i=k-1;i>=0;i--) cout<<s[i]; Cout<<endl;
for (int i=0;i<=a.length (); i++) a.clear ();
for (int i=0;i<=b.length (); i++) b.clear ();
} return 0;
}