初次dp

http://acm.pku.edu.cn/JudgeOnline/problem?id=1163

这是我第一次用动态规划来做题。很不熟练啊。

从下往上依次考察(i,j)下面的较大数,并储存起来。

  
    
#include < stdio.h >
#include
< string .h >
int n,input[ 100 ][ 100 ];
long storage[ 100 ][ 100 ];
int d( int i, int j)
{
if (storage[i][j] >= 0 )
return storage[i][j];
return storage[i][j] = input[i][j] + (i == (n - 1 ) ? 0 :(storage[i + 1 ][j] > storage[i + 1 ][j + 1 ] ? storage[i + 1 ][j]:storage[i + 1 ][j + 1 ]));
}
int main()
{
int i,j;
while (scanf( " %d " , & n) != EOF)
{
for (i = 0 ;i < n;i ++ )
for (j = 0 ;j <= i;j ++ )
scanf(
" %d " , & input[i][j]);
memset(storage,
- 1 , sizeof (storage));
for (i = n - 1 ;i >= 0 ;i -- )
for (j = 0 ;j <= i;j ++ )
d(i,j);
printf(
" %ld\n " ,storage[ 0 ][ 0 ]);
}
return 0 ;
}

再次写这个代码:

  
    
#include < stdio.h >

int dp[ 350 ][ 350 ];
int num[ 350 ][ 350 ];
int n;

int DP( int i, int j)
{
if (dp[i][j] >= 0 )
return dp[i][j];
return dp[i][j] = num[i][j] + ((i + 1 < n) ? (DP(i + 1 , j) > DP(i + 1 , j + 1 ) ? DP(i + 1 , j) : DP(i + 1 , j + 1 )): 0 );
// 第一个括号少了,优先级问题
}

int main()
{
int i, j;
while (scanf( " %d " , & n) != EOF)
{
for (i = 0 ; i < n; i ++ )
for (j = 0 ; j <= i; j ++ )
{
scanf(
" %d " , & num[i][j]);
dp[i][j]
= - 1 ; // 用了0, 在DP里判断用 if(dp[i][j] > 0) 超时
}

for (i = n - 1 ; i >= 0 ; i -- )
for (j = 0 ; j <= i; j ++ )
DP(i, j);

printf(
" %d\n " , dp[ 0 ][ 0 ]);
}
return 0 ;
}

你可能感兴趣的:(dp)