码迷,mamicode.com
首页 > 编程语言 > 详细

蓝桥杯 算法训练 ALGO-124 数字三角形

时间:2017-03-31 23:45:24      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:最大   src   height   规模   logs   blog   治法   其他   buffer   

算法训练 数字三角形  
时间限制:1.0s   内存限制:256.0MB
 
问题描述
  (图3.1-1)示出了一个数字三角形。 请编一个程序计算从顶至底的某处的一条路
 径,使该路径所经过的数字的总和最大。
  ●每一步可沿左斜线向下或右斜线向下走;
  ●1<三角形行数≤100;
  ●三角形中的数字为整数0,1,…99;
  技术分享.
  (图3.1-1)
输入格式
  文件中首先读到的是三角形的行数。

  接下来描述整个三角形
输出格式
  最大总和(整数)
样例输入
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
样例输出
30
 
题目解析:
  本题涉及到一种算法——分治法。
  分治法的基本思想:
    分治法可以通俗的解释为:把一片领土分解,分解为若干块小部分,然后一块块地占领征服,被分解的可以是不同的政治派别或是其他什么,然后让他们彼此异化。
    分治法的精髓:
    分--将问题分解为规模更小的子问题;
    治--将这些规模更小的子问题逐个击破;
    合--将已解决的子问题合并,最终得出“母”问题的解。
    技术分享
  将数字三角形放在二维数组中。从倒数第二行开始逐行往上,每个数都加上它的下一行同一列和下一行右列
中最大的那一个数。
  路径最大和即为数组中第一个数。
 
示例代码:
 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStreamReader;
 4 
 5 public class Main {
 6     private static int row;  //行数
 7     private static int[][] arr;
 8     public static void main(String[] args) throws NumberFormatException, IOException {
 9         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10         row = Integer.parseInt(br.readLine());
11         arr = new int[row][row];
12         
13         for(int i = 0; i < row; i++){
14             String[] str = br.readLine().split(" ");
15             for(int j = 0; j <= i; j++){
16                 arr[i][j] = Integer.parseInt(str[j]);
17             }
18         }
19         
20         int maxSum = maxSum(row,arr);
21         
22         System.out.println(maxSum);
23     }
24     /**
25      * 最大和
26      * @param row  行数
27      * @param arr  数组
28      * @return     该路径的最大和
29      */
30     private static int maxSum(int row, int[][] arr) {
31         for(int i = row-2; i >= 0; i--){
32             for(int j = 0; j <= i; j++){
33                 arr[i][j] += maxNum(arr[i+1][j] , arr[i+1][j+1]);
34             }
35         }
36         return arr[0][0];
37     }
38     
39     /**
40      * 求两个数中的最大数
41      * @param a
42      * @param b
43      * @return    最大数
44      */
45     private static int maxNum(int a, int b) {
46         return a>b?a:b;
47     }
48 }

 

蓝桥杯 算法训练 ALGO-124 数字三角形

标签:最大   src   height   规模   logs   blog   治法   其他   buffer   

原文地址:http://www.cnblogs.com/cao-lei/p/6653768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!