Project Euler 18 Maximum path sum I( DP and 记忆化搜索 )
2024-08-31 07:30:31
题意:****求从三角形顶端出发到达底部,所能够得到的最大路径和
方法一:记忆化搜索
/*************************************************************************
> File Name: euler018t2.c
> Author: WArobot
> Blog: http://www.cnblogs.com/WArobot/
> Created Time: 2017年06月28日 星期三 11时01分01秒
************************************************************************/
#include <stdio.h>
#include <inttypes.h>
#define MAX_N 15
int32_t Mat[MAX_N][MAX_N];
int32_t f[MAX_N][MAX_N]; // f[x][y] 代表从点 (x,y) 到最底端的最长路径长度
int32_t DFS(int32_t x , int32_t y) { // 搜索点(x,y)下方路径中的最大值
if (x + 1 == MAX_N) return Mat[x][y];
if (f[x][y] != 0 ) return f[x][y]; // 记忆化,如果(x,y)已经求得下面路径中的最大值,则返回上次记忆的最长路径
int32_t ans1 , ans2;
ans1 = DFS(x + 1 , y) + Mat[x][y];
ans2 = DFS(x + 1 , y + 1) + Mat[x][y];
f[x][y] = ans1 > ans2 ? ans1 : ans2; // 记忆化部分
return f[x][y];
}
int32_t main() {
freopen("euler018input.txt","r",stdin);
for (int32_t i = 0 ; i < MAX_N ; i++) {
for (int32_t j = 0 ; j <= i ; j++) {
scanf("%d",&Mat[i][j]);
}
}
int32_t ret = DFS(0,0);
printf("%d\n",ret);
return 0;
}
方法二:DP
/*************************************************************************
> File Name: euler018.cpp
> Author: WArobot
> Blog: http://www.cnblogs.com/WArobot/
> Created Time: 2017年05月17日 星期三 22时21分32秒
************************************************************************/
#include<bits/stdc++.h>
using namespace std;
const int MAX_N = 15;
int mat[MAX_N + 4][MAX_N + 4];
int main(){
memset(mat,0,sizeof(mat));
freopen("euler018input.txt","r",stdin);
for(int i = 0 ; i < MAX_N ; i++)
for(int j = 0 ; j <= i ; j++) scanf("%d",&mat[i][j]);
printf("mat[1][1] = %d\n",mat[1][1]);
for(int i = MAX_N-1-1 ; i >= 0 ; i--){
for(int j = 0 ; j <= i ; j++){
mat[i][j] += max(mat[i+1][j] , mat[i+1][j+1]);
}
}
printf("ans = %d\n",mat[0][0]);
return 0;
}
最新文章
- [APUE]进程控制(上)
- RFID考试背诵
- modelsim(3) - summary ,issue,tips
- SequoiaDB(巨杉数据库)(社区版)安装配置使用图解
- c# 各种排序算法+找第二大的数+句子单词反转
- Java基础知识强化之网络编程笔记17:Android网络通信之 使用Http的Post方式读取网络数据(基于HTTP通信技术)
- M - 小希的迷宫
- Oracle EBS-SQL (GL-2):从总帐追溯到库存
- MPC8313ERDB不新鲜pkg包裹,把文件放进Ramdisk
- 快速排序(js版本)
- 编辑器phpstrom的快捷键修改
- selenium 使用随笔
- hibernate学习(三) hibernate中的对象状态
- zabbix利用orabbix监控oracle
- volatile足以保证数据同步吗
- 《javascript语言精粹》读书笔记 Item2 对象
- 末学者笔记--shell编程上 1 玄
- io读取遇到的问题
- Error occurred during initialization of VM Could not reserve enough space for object heap
- Android SurfaceView实现跟随手指移动的光标