题目描述
Michael 喜欢滑雪。这并不奇怪,因为滑雪的确很刺激。可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你。Michael 想知道在一个区域中最长的滑坡。区域由一个二维数组给出。数组的每个数字代表点的高度。下面是一个例子:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度会减小。在上面的例子中,一条可行的滑坡为 24-17-16-1(从 24 开始,在 1 结束)。当然 25-24-23-…-3-2-1 更长。事实上,这是最长的一条。
输入格式
输入的第一行为表示区域的二维数组的行数 R 和列数 C。下面是 R 行,每行有 C 个数,代表高度(两个数字之间用 1 个空格间隔)。
输出格式
输出区域中最长滑坡的长度。
输入输出样例
输入 #1
5 5 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
输出 #1
25
说明/提示
对于 100% 的数据,1≤R,C≤100。
正解一定是dp。但我8太会。数据范围很小,直接dfs。当然了,运气糟糕时,暴搜会是o(n^3),会超时。于是写一个记忆化搜索。
这题真的是练习回溯和记忆化搜索的模板题。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; int a,b,tot,ans,temp; int n[105][105]; int map[105][105]; 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) { tot++; ans=max(ans,tot); temp=max(temp,tot); if(x+1<a&&n[x+1][y]<n[x][y]) if(map[x+1][y]>0) { tot+=map[x+1][y]; ans=max(ans,tot); temp=max(temp,tot); tot-=map[x+1][y]; } else dfs(x+1,y); if(x-1>=0&&n[x-1][y]<n[x][y]) if(map[x-1][y]>0) { tot+=map[x-1][y]; ans=max(ans,tot); temp=max(temp,tot); tot-=map[x-1][y]; } else dfs(x-1,y); if(y+1<b&&n[x][y+1]<n[x][y]) if(map[x][y+1]>0) { tot+=map[x][y+1]; ans=max(ans,tot); temp=max(temp,tot); tot-=map[x][y+1]; } else dfs(x,y+1); if(y-1>=0&&n[x][y-1]<n[x][y]) if(map[x][y-1]>0) { tot+=map[x][y-1]; ans=max(ans,tot); temp=max(temp,tot); tot-=map[x][y-1]; } else dfs(x,y-1); tot--; } int main() { a=read();b=read(); for(int i=0;i<a;i++) for(int j=0;j<b;j++) n[i][j]=read(); for(int i=0;i<a;i++) for(int j=0;j<b;j++) { dfs(i,j); map[i][j]=temp; temp=0; } cout<<ans; return 0; }