Description
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
一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度减小。在上面的例子中,一条可滑行的滑坡为 。当然 更长。事实上,这是最长的一条。
Input
输入的第一行表示区域的行数
和列数
。下面是R行,每行有C个整数,代表高度
,
。
Output
输出最长区域的长度。
Sample Input
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
Sample Output
25
Source
SHTSC 2002
解题思路
记忆化搜索 or DP
- 记忆化搜索:记录一下每个点的值,然后就爆搜就好了
- DP:因为必须从低到高,所以可以记录每个点的位置,然后排序矩阵。每个点扩展四个点,如果可以到达,那么更新四个方向。
记忆化搜索
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int w[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int f[200][200],n,m,a[200][200],Gun;
bool check(int x,int y){
return (x>=1&&x<=n&&y>=1&&y<=m);
}//边界
int demo(int x,int y){
if(f[x][y]!=0)return f[x][y];//如果这个点找过了,就直接返回
for(int i=0;i<4;i++){
int xx=w[i][0]+x,yy=w[i][1]+y;
if(a[xx][yy]<a[x][y]&&check(xx,yy))
f[x][y]=max(f[x][y],demo(xx,yy)+1);//更新最大值
}
if(f[x][y]==0)//如果四个方向都不行,赋1
f[x][y]=1;
return f[x][y];
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&a[i][j]);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
if(f[i][j]==0)
f[i][j]=demo(i,j);
Gun=max(Gun,f[i][j]);
}
printf("%d",Gun);
}
DP
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct DT{
int x,y,s;
}a[100100];
const int w[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int f[200][200],v[200][200],n,m,num,Gun;
bool cmp(const DT&k,const DT&l){
return k.s<l.s;
}
bool check(int x,int y){
return (x>=1&&x<=n&&y>=1&&y<=m);
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
scanf("%d",&v[i][j]);
a[++num].s=v[i][j],a[num].x=i,a[num].y=j;//记录位置
}
sort(a+1,a+1+num,cmp);//排个序
for(int i=1;i<=num;i++){
int x=a[i].x,y=a[i].y;
for(int j=0;j<4;j++){
int wx=x+w[j][0],wy=y+w[j][1];
if(check(wx,wy)&&v[x][y]<v[wx][wy])//如果可以到达
f[wx][wy]=max(f[wx][wy],f[x][y]+1); //更新
}
Gun=max(Gun,f[x][y]);
}
printf("%d",Gun+1);
}