洛谷 - [SHOI2002]滑雪 (dp)

题目链接
题意:
给你一个二维数组,每个点有一个权值(山的高度),现在只能从高度高的点往下移动,问最长路径是多少。

思路:
dp思想,寻找最优子结构,很容易知道,在一个点,以这个点为结束点的最长路径为:以其四周(上下左右)的点为结束点的前一个点的最大值加一(前提是他的高度大于结束点)。
本来以为自己亲手a掉了,高兴坏了,结果还是wa了,为什么呢?以为dp思想要求无后效性(也就是前面的结果对后面的子结构不会有影响,官方定义为:某阶段的状态一旦确定,则此后过程的演变不再受此前各种状态及决策的影响),那么我们就要用一个优先队列作为辅助,让高度低的点排在前面(因为低的点最开始不可能对高的点有影响,而先算高的点,后面的低的点会被前面的高的点所约束)

AC代码

#include <bits/stdc++.h>
inline int read(){char c = getchar();int x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
const int N = 1e5 + 5;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const unsigned long long mod = 998244353;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
struct node
{
    int x,y,h;
    bool operator <(const node &a)const//结构体内镶排序
    {
        return h < a.h;
    }
};
priority_queue<node> q;
int arr[105][105];
int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    int n,m,Max = 0;
    cin >> n >> m;
    int dp[n+5][m+5] = {0};
    for(int i = 1;i <= n;i++)
    {
        for(int j = 1;j <= m;j++)
        {
            cin >> arr[i][j];
            dp[i][j] = 1;
            q.push({i,j,arr[i][j]});
        }
    }
    while(!q.empty())
    {
        int xx = q.top().x,yy = q.top().y,hh = q.top().h;
        q.pop();
        int a = 0,b = 0,c = 0,d = 0;
        if(arr[xx-1][yy] > hh) a = dp[xx-1][yy];
        if(arr[xx][yy-1] > hh) b = dp[xx][yy-1];
        if(arr[xx+1][yy] > hh) c = dp[xx+1][yy];
        if(arr[xx][yy+1] > hh) d = dp[xx][yy+1];
        dp[xx][yy] = max(a,max(b,max(c,d))) + 1;//动态转移方程
        Max = max(dp[xx][yy],Max);
    }
    cout << Max << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值