本題來源洛谷https://www.luogu.com.cn/problem/P1216html
題面以下:ios
觀察下面的數字金字塔。spa
寫一個程序來查找從最高點到底部任意處結束的路徑,使路徑通過數字的和最大。每一步能夠走到左下方的點也能夠到達右下方的點。code
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
在上面的樣例中,從 7 \to 3 \to 8 \to 7 \to 57→3→8→7→5 的路徑產生了最大orm
第一個行一個正整數 rr ,表示行的數目。htm
後面每行爲這個數字金字塔特定行包含的整數。blog
單獨的一行,包含那個可能獲得的最大的和。ci
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
30
【數據範圍】
對於 100\%100% 的數據,1\le r \le 10001≤r≤1000,全部輸入在 [0,100][0,100] 範圍內。get
代碼以下:input
#include<iostream> #include<algorithm> using namespace std; int dp[1000+5][1000+5],w[1000+5][1000+5]; int main() { int n; cin>>n; for(int i=1;i<=n;i++) for(int j=1;j<=i;j++) { cin>>w[i][j]; if(i==n) dp[i][j]=w[i][j]; } for(int i=n-1;i>=1;i--) for(int j=1;j<=i;j++){ { dp[i][j]=max(w[i][j]+dp[i+1][j],w[i][j]+dp[i+1][j+1]); } } cout<<dp[1][1]<<endl; }