您的位置:首页 > 其它

POJ 2760: 数字三角形

2016-07-09 17:42 337 查看
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
int[][] triNumbers = new int[101][101];//0-100内
int[][] triMaxs = new int[101][101];

Scanner in = new Scanner(System.in);
int nrow = in.nextInt();//行数
for(int i=0;i<nrow;i++)//行
{
for(int j=0;j<=i;j++)//行内
{
triNumbers[i][j] = in.nextInt();
}
}
in.close();
for(int i = nrow-1;i>=0;i--)
{
for(int j=i;j>=0;j--)//行内
{
if(nrow==i)
triMaxs[i][j] = triNumbers[i][j];//最后一行
else
triMaxs[i][j] =  Math.max(triMaxs[i+1][j], triMaxs[i+1][j+1])+triNumbers[i][j];
}
}
System.out.println(triMaxs[0][0]);
}
}


题目:

总时间限制: 1000ms 内存限制: 65536kB描述
7
3   8
8   1   0
2   7   4   4
4   5   2   6   5

(图1)


图1给出了一个数字三角形。从三角形的顶部到底部有很多条不同的路径。对于每条路径,把路径上面的数加起来可以得到一个和,你的任务就是找到最大的和。

注意:路径上的每一步只能从一个数走到下一层上和它最近的左边的那个数或者右边的那个数。输入输入的是一行是一个整数N (1 < N <= 100),给出三角形的行数。下面的N行给出数字三角形。数字三角形上的数的范围都在0和100之间。输出输出最大的和。样例输入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

样例输出
30

来源翻译自 IOI 1994 的试题一些些总结:This problem is adopted in Programming Guide. It adapts dynamic planning to solving the problem, which takes less space and time than the measure of recursion.Although the algorithm was described clearly, I still got "WA" when first pubmitted my src.After I compared the standard answer with mine , I found that the standard one adds 10 to the max boundary of the array.Well, after checking, I find in the circulation,i or j can be 101,so the max boundary must be no less than 101.The result always goes back on a careless man...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: