洛谷:P1434【滑雪】

题目描述

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(从24开始,在1结束)。当然25-24-23―┅―3―2―1更长。事实上,这是最长的一条。

输入输出格式

输入格式:

输入的第一行为表示区域的二维数组的行数R和列数C(1≤R,C≤100)。下面是R行,每行有C个数,代表高度(两个数字之间用1个空格间隔)。

输出格式:

输出区域中最长滑坡的长度。


        很明显,这题用动态规划是比较难做的,所以我们可以考虑dfs,对每个点都搜出它可以经过的最大高度,然后求出每个点的最大值。于是就有了代码:

#include<bits/stdc++.h>
using namespace std;
#define mmax 0x3f3f3f
#define maxrc 100 + 5
const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

int mmap[maxrc][maxrc];
int dp[maxrc][maxrc];
int r, c;

bool check(int x, int y){
	return 0 < x && x <= r && 0 < y && y <= c;
}

int dfs(int x, int y){
	for(int i = 0; i < 4; i++){
		int tx = x + dir[i][0];
		int ty = y + dir[i][1];
		
		if(check(tx, ty) && mmap[tx][ty] > mmap[x][y]){
			dp[x][y] = max(dfs(tx, ty) + 1, dp[x][y]);
		}
	}
	
	if(!dp[x][y]) dp[x][y] = 1;
	return dp[x][y];
}

int main(void){
	cin >> r >> c;
	
	for(int i = 1; i <= r; i++){
		for(int j = 1; j <= c; j++){
			cin >> mmap[i][j];
		}
	}
	
	dp[1][1] = 1;
	int tmp = -mmax;
	for(int i = 1; i <= r; i++){
		for(int j = 1; j <= c; j++){
			tmp = max(dfs(i, j), tmp);
		}
	}
	
	printf("%d\n", tmp);
	return 0;
}

        然后你就得了90分~。所以我们需要记忆化搜索:

#include<bits/stdc++.h>
using namespace std;
#define mmax 0x3f3f3f
#define maxrc 100 + 5
const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

int mmap[maxrc][maxrc];
int dp[maxrc][maxrc];
int r, c;

bool check(int x, int y){
	return 0 < x && x <= r && 0 < y && y <= c;
}

int dfs(int x, int y){
	if(dp[x][y] && (x != 1 && y != 1)) return dp[x][y];
	
	for(int i = 0; i < 4; i++){
		int tx = x + dir[i][0];
		int ty = y + dir[i][1];
		
		if(check(tx, ty) && mmap[tx][ty] > mmap[x][y]){
			dp[x][y] = max(dfs(tx, ty) + 1, dp[x][y]);
		}
	}
	
	if(!dp[x][y]) dp[x][y] = 1;
	return dp[x][y];
}

int main(void){
	cin >> r >> c;
	
	for(int i = 1; i <= r; i++){
		for(int j = 1; j <= c; j++){
			cin >> mmap[i][j];
		}
	}
	
	dp[1][1] = 1;
	int tmp = -mmax;
	for(int i = 1; i <= r; i++){
		for(int j = 1; j <= c; j++){
			tmp = max(dfs(i, j), tmp);
		}
	}
	
	printf("%d\n", tmp);
	return 0;
}

美滋滋~

猜你喜欢

转载自blog.csdn.net/qq_35436309/article/details/82989592