problem

Hello everyone! I have a big big big trouble regarding the program below. This is supposed to be implementation of the "longest common subsequent" in dynamic programming, using memoization technique. But i'm trying for 2 days and I still can't figure out where the bug is.

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
  // c++ code
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("dp.in");
ofstream fout("dp.out");
int DP[100][100],n,m,i,j,result,aux;
char S[101],T[101];
int LCS(int i,int j)
{
    if(i==0 || j==0)
    return 0;
    if(DP[i][j]!=-1)
    return DP[i][j];
    else
    if(S[i]==T[j])
    result=1+LCS(i-1,j-1);
    else
    result=max(LCS(i,j-1),LCS(i-1,j));
    DP[i][j]=result;
    return result;
}
int main()
{
fin.get(S,101);
n=strlen(S);
fin.get();
fin.get(T,101);
m=strlen(T);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
DP[i][j]=-1;
for(i=n;i>=1;i--)
{
    aux=S[i];
    S[i]=S[i-1];
    S[i-1]=aux;
}
for(i=m;i>=1;i--)
{
    aux=T[i];
    T[i]=T[i-1];
    T[i-1]=aux;
}
fout<<LCS(n,m)<<endl;
for(i=1;i<=n;i++)
{for(j=1;j<=m;j++)
fout<<DP[i][j]<<" ";
fout<<"\n";}
return 0;
}

I think the recurence is obvious enough, and that we have to search the longest common subsequence of S and T strings.
In order to use memoization tech, i declared a DP[][] matrix in which to store the results of the subproblems, and the lower-right corner is the expected result ( size of the lcs). But even if it outputs the right result, it doesn't output the right matrix. Some values weren't passed through as they kept their '-1' value. So, if you've got any idea, please tell me, it's very important, especially because I'm not that good at dynamic programming. Thanks in advance!
Normally in good programming technique, you put {} after your if then else statements. Try that
It's fine now, i figured it out. And no offense, but "{}" is optional if the body of a loop or statement has size of less than or equal to one instruction.
Topic archived. No new replies allowed.