-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLCS.cpp
71 lines (60 loc) · 1.11 KB
/
LCS.cpp
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
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>
using namespace std;
string str1,str2;
int dp[1000][1000];
int LCS(int a, int b){
if(dp[a][b]!=-1) return dp[a][b];
if(a==str1.length()||b==str2.length()) return 0;
int p=0;
if(str1[a]==str2[b]) p=1+LCS(a+1,b+1);
else p=max(LCS(a+1,b),LCS(a,b+1));
return dp[a][b]=p;
}
string ans;
void printLCS(int a, int b){
if(a==str1.length()||b==str2.length()){
cout<<ans<<endl;
return;
}
if(str1[a]==str2[b]){
ans+=str1[a];
printLCS(a+1,b+1);
} else{
if(dp[a+1][b]>dp[a][b+1])
printLCS(a+1,b);
else
printLCS(a,b+1);
}
}
void printALL(int a, int b){
if(a==str1.length()||b==str2.length()){
cout<<ans<<endl;
return;
}
if(str1[a]==str2[b]){
ans+=str1[a];
printALL(a+1,b+1);
ans.erase(ans.end()-1);
} else{
if(dp[a+1][b]>dp[a][b+1])
printALL(a+1,b);
else if(dp[a+1][b]<dp[a][b+1])
printALL(a,b+1);
else{
printALL(a+1,b);
printALL(a,b+1);
}
}
}
int main(){
cin>>str1>>str2;
memset(dp,-1,sizeof dp);
cout<<"LCS-size: "<<LCS(0,0)<<endl;
cout<<"LCS: ";
ans.clear();
printLCS(0,0);
ans.clear();
cout<<"All LCS: \n";
printALL(0,0);
return 0;
}