标签:超时 turn pre open route 提示 following sizeof either
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
30
1 #include <bits/stdc++.h> 2 using namespace std; 3 int a[105][105],n; 4 int maxsum(int i,int j) { 5 if(i==n) { 6 return a[i][j]; 7 } 8 int sum1=maxsum(i+1,j); 9 int sum2=maxsum(i+1,j+1); 10 return a[i][j]+max(sum1,sum2); 11 } 12 int main() { 13 cin>>n; 14 for(int i=1; i<=n; i++) { 15 for(int j=1; j<=i; j++) { 16 cin>>a[i][j]; 17 } 18 } 19 cout<<maxsum(1,1); 20 21 return 0; 22 }
所以选择动态规划,在每一步求得最大值时记录下来,下次就无须再次计算。
1 #include <bits/stdc++.h> 2 using namespace std; 3 int a[105][105],n; 4 int ms[105][105]; 5 int maxsum(int i,int j) { 6 if(i==n) { 7 return a[i][j]; 8 } 9 if(ms[i+1][j]==-1) { 10 ms[i+1][j]=maxsum(i+1,j); 11 } 12 if(ms[i+1][j+1]==-1) { 13 ms[i+1][j+1]=maxsum(i+1,j+1); 14 } 15 return a[i][j]+max(ms[i+1][j],ms[i+1][j+1]); 16 } 17 int main() { 18 cin>>n; 19 memset(ms,-1,sizeof(ms)); 20 for(int i=1; i<=n; i++) { 21 for(int j=1; j<=i; j++) { 22 cin>>a[i][j]; 23 } 24 } 25 cout<<maxsum(1,1); 26 27 return 0; 28 }
标签:超时 turn pre open route 提示 following sizeof either
原文地址:https://www.cnblogs.com/aiqinger/p/12591373.html