您的位置:首页 > 其它

POJ 1088(dp)

2016-04-10 17:14 357 查看
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

(说实话,这是我第一次写dp,这次的周赛打的我心塞-_-,西湖的水,我的泪)

题目是中文,所以就无所谓题意了。

大致思想:用一个a[][]数组来存储地图,然后用一个dir[][]数组来存储能往下走的方向。用dp来做。每一步走的时候是与之前所走的无关的,无后效性,且每步走时所需考虑的问题相同,也就是子问题相同。所以可以用动态规划来做。相当于递归下一步的状态与结论,由于本题有4个方向,所以每个方向都需要考虑一下。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>

using namespace std;
int a[200][200], r, c, len[200][200];
int dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};//存储方向

int go(int x, int y)
{
if (len[x][y]) return len[x][y];
int maxx = 0, s;
for (int t = 0; t < 4; t++) {//四种方向都要讨论
int temx = x + dir[t][0], temy = y + dir[t][1];//去到何处
if (temx >= 0 && temx < r && temy >= 0 && temy < c && a[temx][temy] < a[x][y]) {
s = go (temx, temy);
if (s > maxx) maxx = s;
}
}
len[x][y] = maxx + 1;
return maxx + 1;
}

int main()
{
int maxn = 0, st = 0;
cin >> r >> c;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> a[i][j];
}
}
memset (len, 0, sizeof (len));
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
len[i][j] = go (i, j);
if (maxn < len[i][j]) maxn = len[i][j];
}
}
cout << maxn << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: