题目描述
观察下面的数字金字塔。
写一个程序来查找从最高点到底部任意处结束的路径,使路径经过数字的和最大。每一步可以走到左下方的点也可以到达右下方的点。
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
在上面的样例中,从 7→3→8→7→5 的路径产生了最大
输入格式
第一个行一个正整数 r ,表示行的数目。
后面每行为这个数字金字塔特定行包含的整数。
输出格式
单独的一行,包含那个可能得到的最大的和。
输入输出样例
输入 #1
5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
输出 #1
30
说明/提示
【数据范围】
对于 100% 的数据,1≤r≤1000,所有输入在 [0,100] 范围内。
题目翻译来自NOCOW。
USACO Training Section 1.5
IOI1994 Day1T1
这是一道动归题。dfs可以得60分。主要是记录一下回溯的语法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<cstdio> #include<cmath> using namespace std; int a; int map[1005][1005]; int ans,temp; int read() { int x=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9') { if(ch=='-') f=-1; ch=getchar(); } while(ch>='0'&&ch<='9') { x=x*10+ch-'0'; ch=getchar(); } return x*f; } void dfs(int x,int y) { temp+=map[x][y]; if(x==a) { ans=max(ans,temp); return ; } dfs(x+1,y); //回溯 temp-=map[x+1][y]; dfs(x+1,y+1); temp-=map[x+1][y+1]; } int main() { a=read(); for(int i=1;i<=a;i++) for(int j=1;j<=i;j++) map[i][j]=read(); dfs(1,1); cout<<ans; return 0; }