滑雪问题详解
总时间限制: 1000ms 内存限制: 65536kB
描述
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。当然25-24-23-…-3-2-1更长。事实上,这是最长的一条。
输入
输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,每行有C个整数,代表高度h,0<=h<=10000。
输出
输出最长区域的长度。
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
题目以及在线测试代码: 平台
思路:
题目
郭炜老师思路视频:链接
注意
1.给数组开辟的空间不能省,应该开到题目要求的最大,不然在平台上跑程序就可能出现 Runtime Error 等错误。
2.测试用例要尽可能丰富,缺乏测试用例可能导致无法及时发现代码的问题。
解法一:人人为我(动态规划)
#include<iostream>
#include<cstdio>
#include<algorithm>
#define NUM 103
using namespace std;
int r,c;
int a[NUM][NUM];
int dp[NUM][NUM];
int dir[4][2] ={{1,0},{-1,0},{0,1},{0,-1}}; //分别判断下面、上面、右边、左边
//保存当前数据在二维数组中的位置以及高度
struct one {
int x;
int y;
int h;
}b[10100];
int cmp(one a, one b) {
return a.h < b.h;
}
int main(){
cin>>r>>c;
int n=0,maxx = 1;
for(int i = 1; i <= r; i++){
for(int j =1; j <= c; j++){
cin>>a[i][j];
dp[i][j] = 1;
b[n].x = i;
b[n].y = j;
b[n].h = a[i][j];
n++;
}
}
//对结构体进行排序
sort(b,b+n,cmp);
//找出现有的n各点的路径最大值,并放入对应的 dp[i][j]二维数组中
for(int i = 0; i < n; i++) {
int now_x = b[i].x ;
int now_y = b[i].y ;
for(int j = 0; j < 4; j++ ){
int now_xx = now_x + dir[j][0];
int now_yy = now_y + dir[j][1];
int p = a[now_xx ][now_yy];
if(now_xx >=1 && now_yy >=1 && now_xx <= r && now_yy <= c && a[now_x][now_y] > p){
dp[now_x][now_y] = max( dp[now_x][now_y] , dp[now_xx][now_yy]+1);
maxx = max(maxx,dp[now_x][now_y]);
}
}
}
cout<<maxx<<endl;
return 0;
}
解法二:我为人人(动态规划)
#include<iostream>
#include<cstdio>
#include<algorithm>
#define NUM 103
using namespace std;
int r,c;
int a[NUM][NUM];
int dp[NUM][NUM];
int dir[4][2] ={{1,0},{-1,0},{0,1},{0,-1}}; //分别判断下面、上面、右边、左边
//保存当前数据在二维数组中的位置以及高度
struct one {
int x;
int y;
int h;
}b[10100];
int cmp(one a, one b) {
return a.h < b.h;
}
int main(){
cin>>r>>c;
int n=0,maxx = 1;
for(int i = 1; i <= r; i++){
for(int j =1; j <= c; j++){
cin>>a[i][j];
dp[i][j] = 1;
b[n].x = i;
b[n].y = j;
b[n].h = a[i][j];
n++;
}
}
//对结构体进行排序
sort(b,b+n,cmp);
//找出现有的n各点的路径最大值,并放入对应的 dp[i][j]二维数组中
for(int i = n-1; i >=0; i--) {
int now_x = b[i].x ;
int now_y = b[i].y ;
for(int j = 0; j < 4; j++ ){
int now_xx = now_x + dir[j][0];
int now_yy = now_y + dir[j][1];
int p = a[now_xx ][now_yy];
if(now_xx >=1 && now_yy >=1 && now_xx <= r && now_yy <= c && a[now_x][now_y] > p){
dp[now_xx][now_yy] = max( dp[now_xx][now_yy] , dp[now_x][now_y]+1);
maxx = max(maxx,dp[now_xx][now_yy]);
}
}
}
cout<<maxx<<endl;
return 0;
}
测试用例
输入:
1 1
1
1 3
2 3 3
2 2
1 2
3 4
4 4
1 2 2 1
1 4 4 1
1 3 3 1
1 2 2 1
3 3
9 1 2
5 6 7
8 4 3
输出:
1 2 3 4 4
其他大佬的测试用例:大量测试用例
ps:
附上:参考代码链接