-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcsmemorizationfinal.cpp
More file actions
55 lines (51 loc) · 1006 Bytes
/
lcsmemorizationfinal.cpp
File metadata and controls
55 lines (51 loc) · 1006 Bytes
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
#include<bits/stdc++.h>
using namespace std;
string str1,str2,longest="";
int CS[100][100];
int LCS(int i,int j)
{
if(str1[i]=='\0' || str2[j]=='\0')
return 0;
else if(CS[i][j]!=-1)
return CS[i][j];
else if(str1[i]==str2[j])
{
CS[i][j] = 1 + LCS(i+1,j+1);
return CS[i][j];
}
else
{
CS[i][j] = max(LCS(i+1,j),LCS(i,j+1));
return CS[i][j];
}
}
void LCS_Display(int i,int j)
{
if(str1[i]=='\0' || str2[j]=='\0')
{
cout<<longest<<endl;
return;
}
else if(str1[i]==str2[j])
{
longest+=str2[j];
LCS_Display(i+1,j+1);
}
else
{
if(CS[i][j+1]>CS[i+1][j])
LCS_Display(i,j+1);
else
LCS_Display(i+1,j);
}
}
int main()
{
memset(CS,-1,sizeof(CS));
int result;
cin>>str1>>str2;
result = LCS(0,0);
cout<<result<<endl;
LCS_Display(0,0);
return 0;
}