The Triangle
前言:
最开始用递归从上到下进行暴力穷举解答,发现时间超了(意料之中);
然后变换思路,采用动态递归的方法从下到上进行计算比较,就过了,下面给出两种解法;
Time Limit: 1000ms, Special Time Limit:2000ms, Memory Limit:32768KB
Problem 10014 : No special judgement
Problem description
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.
Input
Your program is to read from standard input. The first line contains one integer T, the number of test cases, for each test case: the first line contain a 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 for each test case one line.
Sample Input
1
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample Output
30
代码1(递归,穷举)
#include<bits/stdc++.h>
using namespace std;
int a[101][101]={0};
int f(int n,int x,int y,int sum) {
if(x==n-1)
return sum;
int p=f(n,x+1,y,sum+a[x+1][y]);
int q=f(n,x+1,y+1,sum+a[x+1][y+1]);
return max(p,q);
}
int main() {
int t;
cin>>t;
while(t--) {
int n;
cin>>n;
me
for(int i=0; i<n; i++)
for(int j=0; j<=i; j++)
cin>>a[i][j];//完成输入
cout<<f(n,0,0,a[0][0])<<'\n';
}
}
代码2(动态规划)
#include<iostream>
using namespace std;
int a[101][101]={0};
int main() {
int t;
cin>>t;
while(t--) {
int n;
cin>>n;
memset(a,0,sizeof(a));///初始化
for(int i=0; i<n; i++)
for(int j=0; j<=i; j++)
cin>>a[i][j];//完成输入
for(int i=n-2;i>=0;i--){
for(int j=0;j<=i;j++){
a[i][j]+=max(a[i+1][j],a[i+1][j+1]);//从下方选出最大的路径
}
}
cout<<a[0][0]<<endl;
}
}
总结
从上到下选择,选择的分岔路越来越多,暴力穷举,就很容易超时;
从下往上,分岔路越来越少,整个程序简单易懂明了。