learning DP with baby steps this problem of topcoder div2 250 SRM 467 is probably the easiest DP on topcoder PROBLEM LINK SUPER SUM
a basic O(n^3) algorithm does the desired job of filling a DP matrix
algo in pseudocode
declare a matrix ar[15][15]
[parameters k and n have already been passed]
for i in range (0,15)
ar[0][i] = i
for i in range (0,15)
for j in range (0,15)
for k in range (0,j)
ar[i][j]=ar[i][j]+ar[i-1][k]
return ar[k][n]
code:-
class ShorterSuperSum {
public:
int calculate(int k, int n) {
int ar[15][15];
memset(ar,0,225*sizeof(int));
for (int i=0;i<15;i++)
{
ar[0][i]=i;
}
for(int i=1;i<15;i++)
{
for(int j=0;j<15;j++)
{
for(int k=0;k<=j;k++)
{
ar[i][j]+=ar[i-1][k];
}
}
}
return ar[k][n];
}
};
but here the job was easy as the states have been clearly defined still having trouble in doing a DP problem in which you start thinking from scratch but will do it asap :)
a basic O(n^3) algorithm does the desired job of filling a DP matrix
algo in pseudocode
declare a matrix ar[15][15]
[parameters k and n have already been passed]
for i in range (0,15)
ar[0][i] = i
for i in range (0,15)
for j in range (0,15)
for k in range (0,j)
ar[i][j]=ar[i][j]+ar[i-1][k]
return ar[k][n]
code:-
class ShorterSuperSum {
public:
int calculate(int k, int n) {
int ar[15][15];
memset(ar,0,225*sizeof(int));
for (int i=0;i<15;i++)
{
ar[0][i]=i;
}
for(int i=1;i<15;i++)
{
for(int j=0;j<15;j++)
{
for(int k=0;k<=j;k++)
{
ar[i][j]+=ar[i-1][k];
}
}
}
return ar[k][n];
}
};
but here the job was easy as the states have been clearly defined still having trouble in doing a DP problem in which you start thinking from scratch but will do it asap :)
No comments:
Post a Comment