7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30
递推代码O(n
2
)
//#include <bits/stdc++.h> #include <iostream> #include <cstdio> #include <cmath> #include<cstring> #include <algorithm> #include <queue> #include<map> using namespace std; typedef long long ll; const ll inf = 1e13; const int mod = 1000000007; const int mx = 150; //check the limits, dummy typedef pair<int, int> pa; const double PI = acos(-1); ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } #define swa(a,b) a^=b^=a^=b #define re(i,a,b) for(int i=(a),_=(b);i<_;i++) #define rb(i,a,b) for(int i=(b),_=(a);i>=_;i--) #define clr(a) memset(a, 0, sizeof(a)) #define lowbit(x) ((x)&(x-1)) #define mkp make_pai //void sc(int& x) { scanf("%d", &x); }void sc(int64_t& x) { scanf("%lld", &x); }void sc(double& x) { scanf("%lf", &x); }void sc(char& x) { scanf(" %c", &x); }void sc(char* x) { scanf("%s", x); } int n, m, k,ans; int high[mx]; int a[mx][mx], dp[mx][mx]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); while (~scanf("%d",&n)) { clr(dp),clr(a); re(i, 1, n + 1)re(j,1,i+1)scanf("%d",&a[i][j]); re(j, 1, n + 1)dp[n][j] = a[n][j]; for (int i = n - 1; i >= 1; i--) for (int j = 1; j <= i; j++) dp[i][j] = a[i][j] + max(dp[i + 1][j], dp[i + 1][j + 1]); printf("%d\n",dp[1][1]); } return 0; }
下面用递推+记忆化搜索也是O(n2)
//#include <bits/stdc++.h> #include <iostream> #include <cstdio> #include <cmath> #include<cstring> #include <algorithm> #include <queue> #include<map> using namespace std; typedef long long ll; const ll inf = 1e13; const int mod = 1000000007; const int mx = 150; //check the limits, dummy typedef pair<int, int> pa; const double PI = acos(-1); ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } #define swa(a,b) a^=b^=a^=b #define re(i,a,b) for(int i=(a),_=(b);i<_;i++) #define rb(i,a,b) for(int i=(b),_=(a);i>=_;i--) #define clr(a) memset(a, -1, sizeof(a)) #define lowbit(x) ((x)&(x-1)) #define mkp make_pai //void sc(int& x) { scanf("%d", &x); }void sc(int64_t& x) { scanf("%lld", &x); }void sc(double& x) { scanf("%lf", &x); }void sc(char& x) { scanf(" %c", &x); }void sc(char* x) { scanf("%s", x); } int n, m, k,ans; int high[mx]; int a[mx][mx], dp[mx][mx]; int dfs(int i, int j) { if (i == n)return a[i][j]; if (dp[i][j] >= 0)return dp[i][j]; return dp[i][j] = max(dfs(i + 1, j), dfs(i + 1, j + 1)) + a[i][j]; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); while (~scanf("%d",&n)) { clr(dp); re(i, 1, n + 1)re(j,1,i+1)scanf("%d",&a[i][j]); printf("%d\n",dfs(1,1)); } return 0; }