|
| 1 | +#include<iostream> |
| 2 | +using namespace std; |
| 3 | +int lcs_dp(string s,string t){ |
| 4 | + int m=s.size(); |
| 5 | + int n=t.size(); |
| 6 | + int **output=new int*[m+1]; |
| 7 | + for(int i=0;i<=m;i++){ |
| 8 | + output[i]=new int[n+1]; |
| 9 | + } |
| 10 | + //fill the first row |
| 11 | + for(int j=0;j<=n;j++){ |
| 12 | + output[0][j]=0; |
| 13 | + } |
| 14 | + //fill first column |
| 15 | + for(int i=1;i<=m;i++){ |
| 16 | + output[i][0]=0; |
| 17 | + } |
| 18 | + for(int i=1;i<=m;i++){ |
| 19 | + for(int j=1;j<=n;j++){ |
| 20 | + if(s[m-i]==t[n-j]){ |
| 21 | + output[i][j]=1+output[i-1][j-1]; |
| 22 | + } |
| 23 | + else{ |
| 24 | + int a=output[i-1][j]; |
| 25 | + int b=output[i][j-1]; |
| 26 | + int c=output[i-1][j-1]; |
| 27 | + output[i][j]=max(a,max(b,c)); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + return output[m][n]; |
| 32 | +} |
| 33 | +int lcs_mem(string s,string t,int **output){ |
| 34 | + int m=s.size(); |
| 35 | + int n=t.size(); |
| 36 | + if(s.size()==0||t.size()==0){ |
| 37 | + return 0; |
| 38 | + } |
| 39 | + if(output[m][n]!=-1){ |
| 40 | + return output[m][n]; |
| 41 | + } |
| 42 | + int ans; |
| 43 | + if(s[0]==t[0]){ |
| 44 | + ans=1+lcs_mem(s.substr(1),t.substr(1),output); |
| 45 | + } |
| 46 | + else{ |
| 47 | + int a=lcs_mem(s.substr(1),t,output); |
| 48 | + int b=lcs_mem(s,t.substr(1),output); |
| 49 | + int c=lcs_mem(s.substr(1),t.substr(1),output); |
| 50 | + ans=max(a,max(b,c)); |
| 51 | + } |
| 52 | + output[m][n]=ans; |
| 53 | + return output[m][n]; |
| 54 | +} |
| 55 | +int lcs_mem(string s,string t){ |
| 56 | + int m=s.size(); |
| 57 | + int n=t.size(); |
| 58 | + int **output=new int*[m+1]; |
| 59 | + for(int i=0;i<=m;i++){ |
| 60 | + output[i]=new int[n+1]; |
| 61 | + for(int j=0;j<=n;j++){ |
| 62 | + output[i][j]=-1; |
| 63 | + } |
| 64 | + } |
| 65 | + return lcs_mem(s,t,output); |
| 66 | +} |
| 67 | +int lcs(string s,string t){ |
| 68 | + if(s.size()==0||t.size()==0){ |
| 69 | + return 0; |
| 70 | + } |
| 71 | + if(s[0]==t[0]){ |
| 72 | + return 1+lcs(s.substr(1),t.substr(1)); |
| 73 | + } |
| 74 | + else{ |
| 75 | + int a=lcs(s.substr(1),t); |
| 76 | + int b=lcs(s,t.substr(1)); |
| 77 | + int c=lcs(s.substr(1),t.substr(1)); |
| 78 | + return max(a,max(b,c)); |
| 79 | + } |
| 80 | +} |
| 81 | +int main(){ |
| 82 | + string s,t; |
| 83 | + cin>>s>>t; |
| 84 | + cout<<lcs(s,t)<<endl; |
| 85 | + cout<<lcs_mem(s,t)<<endl; |
| 86 | + cout<<lcs_dp(s,t)<<endl; |
| 87 | + return 0; |
| 88 | +} |
0 commit comments