0002 ALGO1006-蓝桥杯-拿金币

试题 算法训练 拿金币

image

动态规划问题,选取上一步最优的结果加上此步可以获取的金币数量。

import java.util.Scanner;

/**
 * @author HuaWang135608
 * @date 2023.03.11 10:27:18
 * @description [试题 算法训练 拿金币](http://lx.lanqiao.cn/problem.page?gpid=T3000)
 */

public class A1006_TakeGold {
	
	public static void main(String[] args) {
		try (Scanner sc = new Scanner(System.in)) {
			// 数据输入
			int src_n = sc.nextInt();
			// 原始二维矩阵,存储金币数量
			// 简单起见,从 1 开始
			short[][] src = new short[src_n + 1][src_n + 1];
			for (int i=1; i<src.length; ++i) {
				for (int j=1; j<src[i].length; ++j) {
					src[i][j] = sc.nextShort();
				}
			}
			// goldCount[i][j] 表示到达此方格时最多能获得的金币数量
			int[][] goldCount = new int[src_n + 1][src_n + 1];
			// 结果
			int res;
			
			// 数据处理
			for (int i=1; i<src.length; ++i) {
				for (int j=1; j<src[i].length; ++j) {
					// 由于 Java 数组初始化时元素的默认数据均为 0
					// 因此可以简化为以下语句
					goldCount[i][j] = src[i][j] +  
							((goldCount[i - 1][j] > goldCount[i][j - 1]) 
									? goldCount[i - 1][j] : goldCount[i][j - 1]);
					// 只能从当前格子走到右侧或下侧的格子
					// 当前格子也只能来源于上侧([i - 1][j])和左侧([i][j - 1])
					// 选择拿到金币较多的格子作为从开头到当前格子的最优路径
				}
			}
			res = goldCount[src_n][src_n];
			
			// 结果输出
			System.out.println(res);
		}
	}

}
posted @ 2023-03-11 10:54  华王135608  阅读(41)  评论(0)    收藏  举报