问题 D: 数塔问题
时间限制: 1 Sec 内存限制: 128 MB
题目描述
有如下所示的数塔,要求从顶层走到底层,若每一步只能走到相邻的结点,则经过的结点的数字之和最大是多少?
输入
输入数据首先包括一个整数C,表示测试实例的个数,每个测试实例的第一行是一个整数N(1 <= N <= 20),表示数塔的高度,接下来用N行数字表示数塔,其中第i行有个i个整数,且所有的整数均在区间[0,99]内。
输出
对于每个测试实例,输出可能得到的最大和,每个实例的输出占一行。
样例输入
1 5 9 12 15 10 6 8 2 18 9 5 19 7 10 4 16
样例输出
59
#include<cstring>
#include<cstdio>
#include <iostream>
#include <cmath>
using namespace std;
int c,n,a[20][20],maxnum;
void search(int x,int y,int sum)
{
if(x>=n||y>=n)
{
if(sum>maxnum)
maxnum=sum;
return;
}
search(x+1,y,sum+a[x+1][y]);
search(x+1,y+1,sum+a[x+1][y+1]);
}
int main()
{
cin>>c;
while(c--)
{
maxnum=0;
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<=i;j++)
cin>>a[i][j];
search(0,0,a[0][0]);
cout<<maxnum<<endl;
}
return 0;
}
上面这段代码是用深搜DFS写的,但是遇到数据量比较大的情况时,推荐用DP写
放一道相似的题
Cow Bowling
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 9 Accepted Submission(s) : 6
Problem Description
The cows don't use actual bowling balls when they go bowling. They each take a number (in the range 0..99), though, and line up in a standard bowling-pin-like triangle like this:
7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Then the other cows traverse the triangle starting from its tip and moving "down" to one of the two diagonally adjacent cows until the "bottom" row is reached. The cow's score is the sum of the numbers of the cows visited along the way. The cow with the highest score wins that frame.
Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable.
Input
Line 1: A single integer, N <br> <br>Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle.
Output
Line 1: The largest sum achievable using the traversal rules
Sample Input
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30
Source
PKU
#include<iostream>
using namespace std;
int n,a[350][350];
int main()
{
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<=i;j++)
cin>>a[i][j];
for(int i=n-1;i>=1;i--)
for(int j=0;j<i;j++)
{
a[i-1][j]+=max(a[i][j],a[i][j+1]);
}
cout<<a[0][0]<<endl;
return 0;
}