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 @   华王135608  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示