在一座山上,有很多很多珠寶,它們散落在山底通往山頂的每條道路上,不同道路上的珠寶的數目也各不相同.下圖爲一張藏寶地圖:
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
”奪寶奇兵”從山下出發,到達山頂,如何選路才能得到最多的珠寶呢?在上圖所示例子中,按照5->7->8->3->7的順序,將得到最大值30
[輸入]
第一行正整數N(100>=N>1),表示山的高度
接下來有N行非負整數,第i行有i個整數(1<=i<=N),表示山的第i層上從左到右每條路上的珠寶數目
[輸出]
一個整數,表示從山底到山頂的所能得到的珠寶的最大數目.
數字三角形問題,記憶化搜索即可
#include <iostream>
#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <cstring>
#include <cstdio>
#include <set>
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include<iomanip>
#define SIS std::ios::sync_with_stdio(false)
#define ll long long
#define INF 0x3f3f3f3f
const int mod = 1e9 + 7;
const double esp = 1e-5;
const double PI = 3.141592653589793238462643383279;
using namespace std;
const int N = 1e7 + 5;
const int maxn = 1 << 20;
ll powmod(ll a, ll b) { ll res = 1; a %= mod; while (b >= 0); for (; b; b >>= 1) { if (b & 1)res = res * a % mod; a = a * a % mod; }return res; }
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
/*void chafen(int l, int r, int k) {//差分函數
p[l] += k;
p[r + 1] -= k;
}*/
/*************************************************************/
int a[105][105];
int dp[105][105];int n;
int solve(int i, int j) {
if (dp[i][j] >= 0)
return dp[i][j];
else {
return dp[i][j] = a[i][j] + (i==n?0:max(solve(i + 1, j), solve(i + 1, j + 1)));
}
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= i; j++)
cin >> a[i][j];
memset(dp, -1, sizeof(dp));
int ans = -INF;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= i; j++)
ans = max(ans, solve(i, j));
cout << ans << endl;
return 0;
}
/*
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
*/