OpenJudge 1088 滑雪

总时间限制: 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

解题思路

采用“人人为我”式,从低到高计算,每个点的maxPath是其上下左右比它低的点的最大maxPath+1。

如何实现排序,将各点存储在一个新数组中进行排序,复习了排序函数的使用。

由于不熟悉sort函数,参考了别人的代码,算是一个教训,多练练这道题。

AC代码

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

int map[105][105];//存储高度
int maxPath[105][105];
int dir[4][2] = { {1,0},{0,1},{-1,0},{0,-1} };

struct Node
{
    int x;
    int y;
    int h;
    bool operator <(const Node &f)const
    {
        return h < f.h;
    }
}n[10100];

int main() {
    int r, c;
    int cnt = 0;//n[]中的角标
    int ans = 1;
    cin >> r >> c;
    for (int i = 1; i <= r; i++)//第零行和第零列空出来,统一了边角情况
    {
        for (int j = 1; j <= c; j++)
        {
            cin >> map[i][j];
            maxPath[i][j] = 1;//初始化为1
            n[cnt].x = i;
            n[cnt].y = j;
            n[cnt].h = map[i][j];//读入结点数据,为排序做准备
            cnt++;
        }
    }
    sort(n, n + cnt);
    for (int i = 0; i < cnt; i++)//从低到高遍历所有点
    {
        int x = n[i].x;
        int y = n[i].y;
        for (int j = 0; j < 4; j++)//上下左右四个方向
        {
            int xx = x + dir[j][0];
            int yy = y + dir[j][1];
            if (xx >= 1 && xx <= r && yy >= 1 && yy <= c && map[x][y] > map[xx][yy])//每经过一个点(x,y) ,更新自己 
            {
                maxPath[x][y] = max(maxPath[x][y], maxPath[xx][yy] + 1);
                ans = max(ans, maxPath[x][y]);
            }
        }
    }
    cout << ans << endl;
    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/yun-an/p/10964069.html