真的很重要!!不管是面试还是实际应用还是acm比赛!
原理在dp中属于好理解的..
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int c[100][100];
int b[100][100];
int countlength=0;
void LCS_Length (string x, string y)
{
int m =x.size();
int n =y.size();
for (int i = 0; i <= m; i++)
c[i][0] = 0;
for (int i = 0; i <= n; i++)
c[0][i] = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (x[i] == y[j])
{
c[i + 1][j + 1] = c[i][j] + 1;
b[i + 1][j + 1] = 0;
}
else if (c[i][j + 1] >= c[i + 1][j])
{
c[i + 1][j + 1] = c[i][j + 1];
b[i + 1][j + 1] = 1;
}
else
{
c[i + 1][j + 1] = c[i + 1][j];
b[i + 1][j + 1] = 2;
}
}
}
}
void Print_LCS (string x, int i, int j)
{
if ((i == 0) || (j == 0))
return ;
if (b[i][j] == 0)
{
Print_LCS (x, i - 1, j - 1);
cout << x[i - 1] << ' ';
countlength++;
}
else if (b[i][j] == 1)
Print_LCS (x, i -1, j);
else
Print_LCS (x, i, j - 1);
}
int main()
{
string x,y;
while (cin >> x >> y)
{
LCS_Length (x, y);
Print_LCS (x, x.size(), y.size());
cout << endl;
cout<<"长度是:"<<countlength<<endl;
}
return 0;
}