Tyvj 1079 数字三角形3(DP)

题目链接

水DP。

 1 #include <stdio.h>

 2 #include <string.h>

 3 #include <stdlib.h>

 4 #define INF -2139062144

 5 int p[25][25],dp[26][26];

 6 int max(int a,int b)

 7 {

 8     return a > b? a:b;

 9 }

10 int main()

11 {

12     int i,j,k,n;

13     scanf("%d",&n);

14     for(i = 1;i <= n;i ++)

15     {

16         for(j = 1;j <= i;j ++)

17         {

18             scanf("%d",&p[i][j]);

19         }

20     }

21     memset(dp,128,sizeof(dp));

22     for(i = 1;i <= n;i ++)

23     {

24         dp[n][i] = p[n][i];

25     }

26     for(i = n-1;i >= n/2;i --)

27     {

28         for(j = 1;j <= i;j ++)

29         {

30             dp[i][j] = p[i][j] + max(dp[i+1][j],dp[i+1][j+1]);

31         }

32     }

33     k = dp[n/2][n/2];

34     memset(dp,128,sizeof(dp));

35     dp[n/2][n/2] = k;

36     for(i = n/2-1;i >= 1;i --)

37     {

38         for(j = 1;j <= i;j ++)

39         {

40             if(dp[i+1][j] != INF)

41             dp[i][j] = p[i][j]+dp[i+1][j];

42             if(dp[i+1][j+1] != INF)

43             dp[i][j] = max(dp[i][j],p[i][j]+dp[i+1][j+1]);

44         }

45     }

46     printf("%d\n",dp[1][1]);

47     return 0;

48 }

你可能感兴趣的:(dp)