南阳oj 题目10 skiing

大年初一,开始练习动态规划。
题目:

个人感觉主要思路就是还递归,只不过递归的同时记录结果节省时间,代码还可以进一步优化写成递推公式的形式

代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

int h[105][105];
int db[105][105];
int R,C;
int res;

int max4(int a,int b,int c,int d){
	
	return max(max(a,b),max(c,d));
}

int sc(int y,int x){
	
	int d1=0,d2=0,d3=0,d4=0;

	if(h[y-1][x]<h[y][x]&&y>=1){
		if(db[y-1][x]){
			d1=db[y-1][x];
		}else d1=sc(y-1,x);
	};
	
	if(h[y+1][x]<h[y][x]&&y+1<R){
		if(db[y+1][x]){
			d2=db[y+1][x];
		}else d2=sc(y+1,x);
	};
	
	if(h[y][x-1]<h[y][x]&&x>=1){
		if(db[y][x-1]){
			d3=db[y][x-1];
		}else d3=sc(y,x-1);
	}
	
	if(h[y][x+1]<h[y][x]&&x+1<C){
		if(db[y][x+1]){
			d4=db[y][x+1];
		}else d4=sc(y,x+1);
	};
	db[y][x]+=max4(d1,d2,d3,d4)+1;
	if(db[y][x]>res)res=db[y][x];
	return db[y][x];
}

int main(){
	int N;
	scanf("%d",&N);
	while(N--){
		res=0;
		scanf("%d%d",&R,&C);
		for(int i=0;i<R;i++)
			for(int j=0;j<C;j++){
				scanf("%d",&h[i][j]);
				db[i][j]=0;
			}

		for(int i=0;i<R;i++)
			for(int j=0;j<C;j++){
				if(!db[i][j]){
					sc(i,j);					
				}
			}
		
		printf("%d\n",res);

		
	}
	
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值