HDU 2084 数塔
来源:互联网 发布:vc socket异步编程 编辑:程序博客网 时间:2024/05/17 02:57
Problem Description
在讲述DP算法的时候,一个经典的例子就是数塔问题,它是这样描述的:
有如下所示的数塔,要求从顶层走到底层,若每一步只能走到相邻的结点,则经过的结点的数字之和最大是多少?
已经告诉你了,这是个DP的题目,你能AC吗?
有如下所示的数塔,要求从顶层走到底层,若每一步只能走到相邻的结点,则经过的结点的数字之和最大是多少?
已经告诉你了,这是个DP的题目,你能AC吗?
Input
输入数据首先包括一个整数C,表示测试实例的个数,每个测试实例的第一行是一个整数N(1 <= N <= 100),表示数塔的高度,接下来用N行数字表示数塔,其中第i行有个i个整数,且所有的整数均在区间[0,99]内。
Output
对于每个测试实例,输出可能得到的最大和,每个实例的输出占一行。
Sample Input
1573 88 1 0 2 7 4 44 5 2 6 5
Sample Output
30
解法一 递归算法
import java.io.BufferedInputStream;import java.util.*;public class Main {public static void main(String[] args) {Scanner sc=new Scanner(new BufferedInputStream(System.in));int k=sc.nextInt();for(int i=0;i<k;i++){int m=sc.nextInt();int a[][]=new int[m][m];for(int j=0;j<m;j++){for(int p=0;p<=j;p++){a[j][p]=sc.nextInt();}}System.out.println(fun(m-1,a));}}public static int fun(int m,int a[][]){if(m==0) return a[0][0];for(int i=m;i>0;i--){if((a[m][i]+a[m-1][i-1])>(a[m][i-1]+a[m-1][i-1]))a[m-1][i-1]=a[m][i]+a[m-1][i-1];else{a[m-1][i-1]=a[m][i-1]+a[m-1][i-1];}}return fun(m-1,a);}}
解法二
import java.io.BufferedInputStream;import java.util.*;public class Main {public static void main(String[] args) {Scanner sc=new Scanner(new BufferedInputStream(System.in));int k=sc.nextInt();for(int i=0;i<k;i++){int m=sc.nextInt();int a[][]=new int[m][m];for(int j=0;j<m;j++){for(int p=0;p<=j;p++){a[j][p]=sc.nextInt();}}System.out.println(fun(m,a));}}public static int fun(int m,int a[][]){ for(int i=m-1;i>=0;i--){ for(int j=i;j>0;j--){ if((a[i][j]+a[i-1][j-1])>(a[i][j-1]+a[i-1][j-1])) a[i-1][j-1]=a[i][j]+a[i-1][j-1]; elsea[i-1][j-1]=a[i][j-1]+a[i-1][j-1]; } } return a[0][0];}}
- HDU 2084 数塔
- hdu 2084 数塔
- hdu 2084 数塔
- hdu 2084 数塔
- hdu 2084 数塔
- HDU 2084 数塔
- hdu 2084 数塔
- HDU 2084 数塔
- HDU 2084 数塔
- hdu 2084 数塔
- hdu 2084 数塔
- HDU 2084(数塔)
- HDU 2084 数塔
- HDU-2084数塔
- HDU 2084 数塔
- hdu 2084 数塔
- hdu--2084--数塔
- HDU 2084 数塔
- 百度笔经&面经
- S3C2440看门狗
- Facebook open sources Corona — a better way to do webscale Hadoop
- 2043 —— 密码
- jave学习第六节代码
- HDU 2084 数塔
- js 控制div居中
- embed\vs2008_ucos\bsp\bspmem.h.c 动态内存申请与释放
- 2042 ——不容易系列之二
- POJ 1521 Entropy
- iis url rewrite 學習
- 2041 ——超级楼梯
- Object-c学习之路二(oc内存管理黄金法则1)
- Access restriction: The method XXX from the type XXX is not accessible due to restriction XXX