1088-滑雪问题(动态规划)

滑雪问题描述

Time Limit: 1000MS              Memory Limit: 65536K

Total Submissions: 91928     Accepted: 34740

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

一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度减小。在上面的例子中,一条可滑行的滑坡为24-17-16-1。当然25-24-23-...-3-2-1更长。事实上,这是最长的一条。

Input

输入的第一行表示区域的行数R和列数C(1 <= R,C <= 100)。下面是R行,每行有C个整数,代表高度h,0<=h<=10000。

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

-------------------------------------------------------------------------------------------

c++代码

//使用动态规划解决滑雪问题

#include

using namespace std;

int**T, **countx;

int longth(int x, int y, int R, int C);

int maxlongth(int R, int C){

int teap = longth(0, 0, R, C);

for (int i = 0; i < R; i++){

for (int j = 0; j < C; j++){

if (longth(i, j, R, C)>teap)

teap = countx[i][j];

}

}

return teap;

}

int longth(int x, int y, int R, int C){//

int longthx = 0;

if (countx[x][y]>0)

return countx[x][y];//之前已经遍历过

if (y >= 1 && (T[x][y] > T[x][y - 1]) && longthx < longth(x, y - 1, R, C))

longthx = countx[x][y - 1];//向左走

if (y < C - 1 && (T[x][y] > T[x][y + 1])&& (longthx < longth(x, y + 1, R, C)))

longthx = countx[x][y + 1];//向右走

if (x >= 1 && (T[x][y] > T[x - 1][y]) && (longthx < longth(x - 1, y, R, C)))

longthx = countx[x - 1][y];//向上走

if (x < R - 1 && (T[x][y] > T[x + 1][y])&& (longthx < longth(x + 1, y, R, C)))

longthx = countx[x + 1][y];//向下走  

return countx[x][y] = longthx + 1;//选取四方中最长的那个路径加上1

}

int main(){

int R = 0, C = 0;

cin >> R >> C;

T = new int*[C];

countx = new int*[C];

for (int i = 0; i < R; i++){

T[i] = new int[C];

countx[i] = new int[C];

}

for (int i = 0; i < R; i++){

for (int j = 0; j < C; j++){

cin >> T[i][j];

countx[i][j] = 0;

}

}

cout << maxlongth(R, C) << endl;

for (int i = 0; i < R; i++){

delete[] T[i], countx[i];

}

delete[] T, countx;

return 0;

}

posted @ 2016-08-16 18:04  天下岂有长生不灭者  阅读(1096)  评论(0编辑  收藏  举报