[Skiing] SHOI2002

[Skiing] SHOI2002

topic

Title Description

Michael likes to ski. This is not surprising, because skiing is very exciting. However, in order to gain speed, slippery areas must be downward, and when you slide into the base, you have to up the grade again or wait for the elevator to take you. Michael wanted to know the longest in a landslide area. Region is given by a two-dimensional array. Each number represents the height of the point of the array. Below is an example:

. 1. 5 2. 3. 4
16. 17. 19. 6 18 is
15 24 20 is 25. 7
14. 8 23 is 22 is 21 is
13 is 12 is 10. 11. 9
a person can slide up and down from a point adjacent to one of the four points, if and only if the height will be decreases. In the above example, a feasible landslide 24-17-16-1 (from 24 starts, at the end of 1). Of course 25-24-23- ... 1 longer. In fact, this is the longest one.

Input Format

The first line represents the number of rows of input two-dimensional array region R and columns C. The following is R rows, each row having the number of C, representative of the height (with a space interval between two digits).

Output Format

The longest length of the output area of ​​the landslide.

Sample input and output

Input # 1 replication
. 5. 5
1. 5 2. 3. 4
16. 17. 19. 6 18 is
15 24 20 is 25. 7
14. 8 23 is 22 is 21 is
13 is 12 is 10. 11. 9
output copy # 1
25

Description / Tips

To 100% of the data, 1≤R, C≤100.

analysis

We proceed from each point once dfs, every time you save the maximum.

** Note: ** This question need to use memory storage value, the optimizer, or else a few points out. .
Memory storage: Each point is to be able to walk up to the value recorded, so the next time you come to this point the other point, you can directly add
up to the value of this point, and then return, saving a lot of time.

Other comments in the code. . . . .

Code

#include<iostream>

using namespace std;


int r,c;
int a[105][105];

int d[4][2] = {{0,1},{-1,0},{0,-1},{1,0} };		//上下左右 
bool vis[105][105];				//这里没用到。。。。。 
int  dep[105][105];				//做记忆化存储
 
bool in(int x,int y){					//是否在方阵里面 
	return 1<=x &&x<=r &&1<=y &&y<=c;
}

int ans ;
int  dfs(int x,int y){
	//记忆化,优化 
	if(dep[x][y]){
		return dep[x][y];
	}
	
	//本身长度为1; 
	dep[x][y] = 1;
	
	for(int i=0;i<4;i++){
		int tx = x+d[i][0];
		int ty = y+d[i][1];
		if(in(tx,ty) && a[tx][ty]<a[x][y] ){			
			dfs(tx,ty);
			//如果往tx,ty方向走,会得到的长度,
			//和原来比较取更长的那个值。 
			dep[x][y] = max(dep[x][y],dep[tx][ty]+1);
		}
	}
	return dep[x][y];	//保存本次的长度 
}
int main(){
	cin>>r>>c;
	for(int i=1;i<=r;i++){
		for(int j=1;j<=c;j++){
			cin>>a[i][j];
		}
	}
	
	//从每个点开始dfs 每次保存最长 
	for(int i=1;i<=r;i++){
		for(int j=1;j<=c;j++){
			ans = max(ans,dfs(i,j));
		}
	}
	cout<<ans<<endl;
	return 0;
}
Published 75 original articles · won praise 1 · views 3640

Guess you like

Origin blog.csdn.net/A793488316/article/details/104726272