0

I have used Dynamic Programming to find longest common sub-sequence b/w two strings. What is wrong in the code. Why it always gives answer as 0?

#include<bits/stdc++.h>
using namespace std;

int dp[20][20];
void initialize()
{
    for(int i=0;i<20;i++)
        for(int j=0;j<20;j++)
            dp[i][j]=-1;
}
int lcs(string a,string b,int m,int n)
{
    if(m==0||n==0) 
        return 0;
    if(dp[m][n]!=-1) 
        return dp[m][n];
    if(a[m-1]==b[n-1]) 
        return  dp[m-1][n-1] = 1+lcs(a,b,m-1,n-1);
    if(a[m-1]!=b[n-1])
        return dp[n-1][m-1]=max(dp[n][m-1]=lcs(a,b,n,m-1),dp[n-1][m]=lcs(a,b,n-1,m));
}
int main()
{
    string a="AGGTAB",b="GXTXAYB";

    cout<<lcs(a,b,a.length(),b.length());

}
kiner_shah
  • 3,939
  • 7
  • 23
  • 37
  • Possible duplicate of [Dynamic Programming: Longest Common Subsequence](https://stackoverflow.com/questions/32288223/dynamic-programming-longest-common-subsequence) – kiner_shah Dec 16 '17 at 05:42

1 Answers1

0
  1. You've forgotten to call initialize()
  2. 18th line, it should be dp[m][n], not dp[m-1][n-1]
  3. Commented 19th line code, as it is no need & for make the code compatible for all compilers

i.e., some compiler may give warning: control reaches end of non-void function [-Wreturn-type]

  1. Made some code change in 20th line, as it seems you confused with variables m & n.

Code:

#include<bits/stdc++.h>
using namespace std;
int dp[20][20];
void initialize()
{
    for(int i=0;i<20;i++)
        for(int j=0;j<20;j++)
            dp[i][j]=-1;
}
int lcs(string a,string b,int m,int n)
{
    if(m==0||n==0) 
        return 0;
    if(dp[m][n]!=-1) 
        return dp[m][n];
    if(a[m-1]==b[n-1]) 
        return dp[m][n] = 1+lcs(a,b,m-1,n-1);
    //if(a[m-1]!=b[n-1])
    return dp[m][n]=max(lcs(a,b,m-1,n),lcs(a,b,m,n-1));
}   
int main()
{
    string a="AGGTAB",b="GXTXAYB";
    initialize();
    cout<<lcs(a,b,a.length(),b.length());
}

Output:

4