矩形滑雪场-DP

david喜欢滑雪。他来到了一个滑雪场,这个滑雪场是一个矩形,为了简便,我们用r行c列的矩阵来表示每块地形。为了得到更快的速度,滑行的路线必须向下倾斜。 例如样例中的那个矩形,可以从某个点滑向上下左右四个相邻的点之一。例如24-17-16-1,其实25-24-23…3-2-1更长,事实上这是最长的一条。

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行: 两个数字r,c(1< =r,c< =100),表示矩阵的行列。 第2..r+1行:每行c个数,表示这个矩阵。

输出格式:

仅一行: 输出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

样例输出

25


代码:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>


using namespace std; 
int r,c;


struct Route // 定义一个结构体来存放每个点的位置信息以及高度 
{
int hang;
int lie;
int h;
}route[11025]; // 转化为一维数组,用来实现从小到大排序 


int maxLen = 0; // 用来存放最大结果 
int s[105][105]; // 存放原始数据,即原始矩形,s[i][j]表示第i行第j列的高度 
int dp[105][105]; // dp[i][j]表示从点(i,j)出发的最长距离 


int cmp(const void *a, const void *b) // 按从小到大排序
{
struct Route r1 = *(struct Route *)a;
struct Route r2 = *(struct Route *)b;
return r1.h - r2.h;  
}


int main(int argc, char** argv) {
int num = 1;
cin >> r >> c;
for(int i=1; i<=r; i++)
for(int j=1; j<=c; j++)

cin >> route[num].h;
route[num].hang = i;
route[num].lie = j;
s[i][j] = route[num].h;
dp[i][j] = 1; // 每点至少有该点本身 
num++;
}  
qsort(route+1,r*c,sizeof(struct Route),cmp);
for(int k=1; k<=r*c; k++)
{  
if(route[k].lie-1>0 && route[k].h > s[route[k].hang][route[k].lie-1]) // 左边有点且该点比左边点高;用原始矩阵s可以方便找到对应的位置即高 
dp[route[k].hang][route[k].lie] = max(dp[route[k].hang][route[k].lie],dp[route[k].hang][route[k].lie-1]+1);
if(route[k].lie+1<=c && route[k].h > s[route[k].hang][route[k].lie+1]) // 与上边左边点同理 
dp[route[k].hang][route[k].lie] = max(dp[route[k].hang][route[k].lie],dp[route[k].hang][route[k].lie+1]+1); 
if(route[k].hang-1>0 && route[k].h > s[route[k].hang-1][route[k].lie]) // 上边有点,且该点比左边点高
dp[route[k].hang][route[k].lie] = max(dp[route[k].hang][route[k].lie],dp[route[k].hang-1][route[k].lie]+1); 
if(route[k].hang+1<=r && route[k].h > s[route[k].hang+1][route[k].lie]) // 下边有点且该点比左边点高
dp[route[k].hang][route[k].lie] = max(dp[route[k].hang][route[k].lie],dp[route[k].hang+1][route[k].lie]+1); 
if(dp[route[k].hang][route[k].lie] > maxLen)
maxLen = dp[route[k].hang][route[k].lie];
}
cout << maxLen << endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/perfect1t/article/details/79520945