project euler 18 Maximum path sum I

来源:互联网 发布:mac 安全模式 编辑:程序博客网 时间:2024/06/11 10:08

题目:

https://projecteuler.net/problem=18

题意:

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
这里写图片描述
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
这里写图片描述
NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)

给出一个15行的数字三角形,从顶端往下走,从当前位置只能走到下一行与当前位置相邻的两个点。选择一条路径,使路径经过点的权值和最大

思路:

定义dp[i][j]为从顶端走到第i行的第j个位置时得到的最大值,显然有状态转移方程:

dp[i][j]=val[i][j]+max(dp[i1][j1],dp[i1][j])

这里重复利用了dp数组,省掉了val数组

代码:

#include <bits/stdc++.h>using namespace std;typedef long long ll;const int N = 100 + 10;int dp[N][N];int main(){    freopen("f:\\data.txt", "r", stdin);    int n = 15;    for(int i = 1; i <= n; ++i)        for(int j = 1; j <= i; ++j)            scanf("%d", &dp[i][j]);    for(int i = 1; i <= n; ++i)        for(int j = 1; j <= i; ++j)            dp[i][j] += max(dp[i-1][j-1], dp[i-1][j]);    int ans = 0;    for(int i = 1; i <= n; ++i)        ans = max(ans, dp[n][i]);    printf("%d\n", ans);    return 0;}
原创粉丝点击