The dynamic programming algorithm is similar to the partition method, and its basic idea is to decompose the problem into several sub-problems, solve the problem first, then get the solution of the original problem from the solution of these sub-problems. Different from the partition method, the sub-problems which are solved by the dynamic programming are often not independent of each other. If divide-and-conquer method is used to solve such problems, the number of sub-problems can be decomposed so that the final solution to the original problem takes exponential time. However, the number of different sub-problems is often only polynomial magnitude. Some sub-problems are repeated for many times when solved by the method of division and treatment. If we can save the answers to the solved sub-problems, and then find out the answers when we need them, we can avoid a lot of repeated computations and get the polynomial-time algorithm. For this purpose, you can use a table to record the answers to all the resolved sub-problems. Regardless of whether the sub-problem is used later, as long as it is calculated, the results are filled into the table. This is the basic idea of dynamic programming.
The dynamic programming algorithm is suitable for solving optimization problems. It is usually possible to design by the following 4 steps: (1) to find out the properties of the optimal solution and characterize its structure. (2) to define the optimal value recursively. (3) Calculate the optimal value in the bottom-down way. (4) The optimal solution is constructed according to the information obtained when calculating the optimal value.
The following is the algorithm for solving the longest common sub-sequence:
#include <iostream>
#include <string>
#define N 20
using namespace Std;
int d[n][n];
int Lcslength (char *a,char *b,int c[][n])
{
int Alen=strlen (a);
int Blen=strlen (b);
for (int i=0;i<=alen;i++)
c[i][0]=0;
for (int j=0;j<=blen;j++)
c[0][j]=0;
for (i=1;i<=alen;i++)
for (j=1;j<=blen;j++)
if (A[i-1]==b[j-1])
c[i][j]=c[i-1][j-1]+1;
Else
c[i][j]=c[i][j-1]>c[i-1][j]?c[i][j-1]:c[i-1][j];
return C[alen][blen];
}
Char *lcs (char *s,char *a,char *b)
{
int c[n][n];
int I=strlen (a);
int J=strlen (b);
int k=lcslength (A,B,C);
s[k]= ' + ';
while (k>0)
{
if (C[i][j]==c[i-1][j])
i--;
else if (C[i][j]==c[i][j-1])
j--;
Else
{
S[--K]=A[I-1];
i--;
j--;
}
}
return s;
}
void Main ()
{
Char *s=new char[n];
Char S1[n];
Char S2[n];
cout<< "Please enter the first string:";
cin>>s1;
cout<< "Please enter a second string:";
cin>>s2;
cout<< "The longest common sub-sequence is:" <<lcs (S,S1,S2) <<endl;
Delete S;
cout<< "Length is" <<lcslength (s1,s2,d) <<endl;
}
Dynamic programming solves the longest common sub-sequence