# 动态规划—数字三角形问题

Time Limit: 1000MS Memory Limit: 65536KB
Problem Description

Input

Output

Example Input

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

Example Output

30

Hint

Author

#include <stdio.h>
#define max(a, b) (a > b)? a: b//define的灵活应用

int a[104][104], n;//定义全局数组和全局变量

void sca()
{
int i, j, max1;
for(i = 0; i < n; i++){
for(j = 0; j <= i; j++){
scanf("%d", &a[i][j]);
if(j == 0 && i != 0)
a[i][j] += a[i-1][j];//动态规划思想
else if(j == i && i != 0)
a[i][j] += a[i-1][j-1];//动态规划思想
else if(i != 0 && j != 0 && j != i)
a[i][j] += max(a[i-1][j-1], a[i-1][j]);//动态规划思想
}
}

i = n-1;
max1 = a[i][0];
for(j = 1; j < n; j++){
if(max1 < a[i][j])
max1 = a[i][j];
}
printf("%d\n", max1);
}

int main()
{
scanf("%d", &n);
sca();
return 0;
}
//不够简洁仍需规范步骤

/***************************************************
User name: jk160630
Result: Accepted
Take time: 0ms
Take Memory: 148KB
Submit time: 2017-01-16 09:20:07
****************************************************/

/a[i][j] = max(a[i+1][j], a[i+1][j+1]) + D[i][j];/不同而提交结果不同，

/***************************************************
User name: jk160630
Result: Wrong Answer
Take time: 0ms
Take Memory: 120KB
Submit time: 2017-01-16 10:31:25
****************************************************/

#include <stdio.h>
#define max(a, b) (a > b)? a: b

int a[104][104], D[104][104], n;

void sca();

int main()
{
scanf("%d", &n);
sca();
return 0;
}

void sca()
{
int i, j;
for(i = 0; i < n; i++)
{
for(j = 0; j <= i; j++)
{
scanf("%d", &D[i][j]);
}
}
for(i = n-1; i >= 0; i--)
{
for(j = 0; j <= i; j++)
{
if(i == n-1)
a[i][j] = D[i][j];
else
{
a[i][j] = max(a[i+1][j], a[i+1][j+1]) + D[i][j];
}
}
}
printf("%d\n", a[0][0]);
}
/***************************************************
User name: jk160630
Result: Accepted
Take time: 0ms
Take Memory: 196KB
Submit time: 2017-01-16 10:40:53
****************************************************/
#include <stdio.h>
#define max(a, b) (a > b)? a: b

int a[104][104], D[104][104], n;

void sca();

int main()
{
scanf("%d", &n);
sca();
return 0;
}

void sca()
{
int i, j, t;
for(i = 0; i < n; i++)
{
for(j = 0; j <= i; j++)
{
scanf("%d", &D[i][j]);
}
}
for(i = n-1; i >= 0; i--)
{
for(j = 0; j <= i; j++)
{
if(i == n-1)
a[i][j] = D[i][j];//动态规划
else
{
t = max(a[i+1][j], a[i+1][j+1]);
a[i][j] = t + D[i][j];//动态规划（减少对重复子问题的运算）
}
}
}
printf("%d\n", a[0][0]);
}
//动态规划 / (自底而上)
04-16 2222

11-04 1万+
03-12 1144
04-16 306
04-21 168
11-09 311
05-04 189
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客