(DP)百练1088:滑雪

百练1088:滑雪

描述

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。

递推公式:(i,j)四周高度比其低,且区域长度最大的那个+1.(“人人为我”式递推)

我的做法是题解1,题解2不大适应……

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxr=110;
struct Node{
    int x,y,w;
    bool operator <(const Node &n )const{
        return this->w<n.w;
    }
}mp[maxr*maxr];

int p[maxr][maxr],dp[maxr][maxr];
int dir[4][2]={-1,0,1,0,0,-1,0,1};

int main(){
    int r,c,cnt=0;
    scanf("%d%d",&r,&c);
    for(int i=1;i<=r;i++){
        for(int j=1;j<=c;j++){
            dp[i][j]=1;
            scanf("%d",&p[i][j]);
            mp[cnt].x=i;
            mp[cnt].y=j;
            mp[cnt++].w=p[i][j];
        }
    }
    //cout<<"***"<<cnt<<endl;

    sort(mp,mp+cnt);
    int ans=-1;
    for(int i=0;i<cnt;i++){
        int x=mp[i].x,y=mp[i].y;
        for(int j=0;j<4;j++){
            int dx=x+dir[j][0],dy=y+dir[j][1];
            if(dx<=0||dy<=0||dx>r||dy>c) continue;
            if(p[x][y]>p[dx][dy])
                dp[x][y]=max(dp[x][y],dp[dx][dy]+1);
        }
        ans=max(ans,dp[x][y]);
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37275680/article/details/81630606