1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
string generateString(int);
void LCS_Length(string &X, string &Y, int, int);
void Print_LCS(string b[10][10], string& X, int, int);
int c[10][10];
string b[10][10];
int main()
{
srand(time(0));
string X, Y;
X = generateString(10);
Y = generateString(10);
LCS_Length(X, Y, X.size(), Y.size());
cout << c[X.size()][Y.size()] << endl;
Print_LCS(b, X, X.size(), Y.size());
cout << endl;
return 0;
}
string generateString(int length)
{
static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int strLen = sizeof(alphabet)-1;
char genRandom;
string str;
for(int i=0; i<length; i++){
genRandom = alphabet[rand()%strLen];
str += genRandom;}
return str;}
void LCS_Length(string &X, string &Y, int m, int n){
for(int i=0; i<=m; i++) {c[i][0] = 0;}
for(int j=0; j<=n; j++) {c[0][j] = 0;}
for(int i=1; i<=m; i++){
for(int j=1; j<=n; j++){
if(X[i-1] == Y[j-1]){
c[i][j] = c[i-1][j-1]+1;
b[i][j] = "Upper Left Corner";}
else if(c[i-1][j] >= c[i][j-1]){
c[i][j] = c[i-1][j];
b[i][j] = "Up";}
else{
c[i][j] = c[i][j-1];
b[i][j] = "Left";} } } }
void Print_LCS(string b[10][10], string &X, int i, int j){
if(i==0 || j==0) return;
if(b[i][j] == "Upper Left Corner"){
Print_LCS(b, X, i-1, j-1);
cout << X[i-1];}
else if(b[i][j] == "Up"){
Print_LCS(b, X, i-1, j);}
else{
Print_LCS(b, X, i, j-1);}}
|