1. 程式人生 > >洛谷P1216數塔(逆向遞推遞歸+記憶化,dp)

洛谷P1216數塔(逆向遞推遞歸+記憶化,dp)

根據 初始 als out 有一個 type lse ++ 遞歸

題目鏈接:https://www.luogu.org/problemnew/show/P1216

題目很簡單,是dp和記憶化搜索的入門練手好題

有一個坑點,全為0的時候,記憶化沒初始化為其它值的話,還是暴力遞歸絕對超時。。(所以記憶化時,根據題目要求分析,一般都初始化為-1)

 1 #include <iostream>
 2 #include <string>
 3 #include <algorithm>
 4 #include <cstdio>
 5 #include <cstring>
 6 #include <cmath>
 7
using namespace std; 8 typedef long long ll; 9 typedef unsigned long long ull; 10 const int maxn=1005; 11 int a[maxn][maxn]; 12 int f[maxn][maxn]; 13 int vis[maxn]; 14 int R; 15 16 int so(int x,int y) 17 { 18 if(f[x][y]!=-1) return f[x][y];//必須!=-1,!=0的話還是萬一都為0還是沒記憶化到Tle 19 if(x==R) 20 { 21 return
f[x][y]=a[x][y]; 22 } 23 24 int l=y,r=y+1; 25 int ls=a[x][y],rs=a[x][y],ans=a[x][y]; 26 if(l>=1) ls+=so(x+1,l); 27 if(r<=R) rs+=so(x+1,r); 28 29 ans=max(ans,ls); 30 ans=max(ans,rs); 31 f[x][y]=max(f[x][y],ans); 32 return f[x][y]; 33 } 34 35 int main() 36 {
37 ios::sync_with_stdio(false); cin.tie(0); 38 39 cin>>R; 40 for(int i=1;i<=R;i++) 41 { 42 for(int j=1;j<=i;j++) 43 { 44 cin>>a[i][j]; 45 f[i][j]=-1; 46 } 47 } 48 49 int ans=so(1,1); 50 51 cout<<ans<<endl; 52 53 return 0; 54 }

完。

洛谷P1216數塔(逆向遞推遞歸+記憶化,dp)