Skip to content

Commit d318535

Browse files
author
Christian Bender
committed
improved the code
1 parent cc9e8d0 commit d318535

File tree

1 file changed

+69
-57
lines changed

1 file changed

+69
-57
lines changed

Dynamic Programming/Longest Common Subsequence.cpp

Lines changed: 69 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -4,72 +4,84 @@ using namespace std;
44

55
void Print(int trace[20][20], int m, int n, string a)
66
{
7-
if (m==0 || n==0)
8-
{
9-
return;
10-
}
11-
if (trace[m][n]==1)
12-
{
13-
Print(trace, m-1, n-1, a);
14-
cout<<a[m-1];
15-
}
16-
else if(trace[m][n]==2)
17-
{
18-
Print(trace, m-1,n, a);
19-
}
20-
else if (trace[m][n]==3)
21-
{
22-
Print(trace, m,n-1, a);
23-
}
7+
if (m==0 || n==0)
8+
{
9+
return;
10+
}
11+
if (trace[m][n]==1)
12+
{
13+
Print(trace, m-1, n-1, a);
14+
cout<<a[m-1];
15+
}
16+
else if(trace[m][n]==2)
17+
{
18+
Print(trace, m-1,n, a);
19+
}
20+
else if (trace[m][n]==3)
21+
{
22+
Print(trace, m,n-1, a);
23+
}
2424
}
2525

2626

2727

28-
int lcs(string a, string b){
29-
int m = a.length(), n = b.length();
30-
int res[m+1][n+1];
31-
int trace[20][20];
32-
for (int i = 0; i < m+1; ++i)
33-
{
34-
for (int j = 0; j < n+1; ++j)
35-
{
36-
if(i==0||j==0)
37-
{
38-
res[i][j] = 0;
39-
trace[i][j]=0;
40-
}
41-
42-
else if(a[i-1]==b[j-1])
43-
{
44-
res[i][j] = 1 + res[i-1][j-1];
45-
trace[i][j]=1; // 1 means trace the matrix in upper left diagonal direction.
46-
}
47-
else
48-
{
49-
if (res[i-1][j]>res[i][j-1])
50-
{
51-
res[i][j]=res[i-1][j];
52-
trace[i][j]=2; // 2 means trace the matrix in upwards direction.
53-
}
54-
else
55-
{
56-
res[i][j]=res[i][j-1];
57-
trace[i][j]=3; // means trace the matrix in left direction.
58-
}
59-
}
60-
}
61-
}
62-
Print(trace, m, n, a);
63-
return res[m][n];
28+
int lcs(string a, string b)
29+
{
30+
int m = a.length(), n = b.length();
31+
int res[m+1][n+1];
32+
int trace[20][20];
33+
34+
// fills up the arrays with zeros.
35+
for (int i = 0; i < m+1; i++)
36+
{
37+
for (int j = 0; j < n+1; j++)
38+
{
39+
res[i][j] = 0;
40+
trace[i][j] = 0;
41+
}
42+
}
43+
44+
for (int i = 0; i < m+1; ++i)
45+
{
46+
for (int j = 0; j < n+1; ++j)
47+
{
48+
if(i==0||j==0)
49+
{
50+
res[i][j] = 0;
51+
trace[i][j]=0;
52+
}
53+
54+
else if(a[i-1]==b[j-1])
55+
{
56+
res[i][j] = 1 + res[i-1][j-1];
57+
trace[i][j]=1; // 1 means trace the matrix in upper left diagonal direction.
58+
}
59+
else
60+
{
61+
if (res[i-1][j]>res[i][j-1])
62+
{
63+
res[i][j]=res[i-1][j];
64+
trace[i][j]=2; // 2 means trace the matrix in upwards direction.
65+
}
66+
else
67+
{
68+
res[i][j]=res[i][j-1];
69+
trace[i][j]=3; // means trace the matrix in left direction.
70+
}
71+
}
72+
}
73+
}
74+
Print(trace, m, n, a);
75+
return res[m][n];
6476
}
6577

6678

6779

6880

6981
int main()
7082
{
71-
string a,b;
72-
cin>>a>>b;
73-
cout<<lcs(a,b);
74-
return 0;
83+
string a,b;
84+
cin>>a>>b;
85+
cout<<lcs(a,b);
86+
return 0;
7587
}

0 commit comments

Comments
 (0)