Luo Gu [P1343] [SHOI2002] [ski] DP Dynamic Programming

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   2   3   4   5
16  17  18  19  6
15  24  25  20  7
14  23  22  21  8
13  12  11  10  9

A person can slide up and down from a point adjacent to one of the four points, if and only if the height is reduced. In the above example, a feasible landslide 24-17-16-11 (from 24 starts, at the end of 1). Of course 25-24-23- ... -3-2-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 C number, representing 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

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

Output # 1

25

analysis of idea:

This question is the DP , from the pushing point to low height higher altitude points , to find the maximum point of its output value. But the dynamic programming must be ordered , so here we want this two-dimensional array expanded into one-dimensional , a sort after it ordered the.

CODE:

#include<iostream>
#include<algorithm> 
#include<cstdio>
using namespace std;
int n,m,g[10010],maxx;
const int dx[5]={0,-1,1,0,0};
const int dy[5]={0,0,0,1,-1};
struct node{
	int value;//值
	int x;//横坐标
	int y;//纵坐标
}f[10010];
bool cmp(node x,node y)
{
	return x.value<y.value;
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
		{
			scanf("%d",&f[(i-1)*m+j].value);
			f[(i-1)*m+j].x=i;f[(i-1)*m+j].y=j;//预处理
		}
	sort(f+1,f+n*m+1,cmp);//排序
	//以下为DP部分
	for(int i=1;i<=n*m;i++)//枚举全部
		for(int j=i-1;j>0;j--)//从高到低
			for(int k=1;k<=4;k++)//四个方向
				if(f[i].x==f[j].x+dx[k]&&f[i].y==f[j].y+dy[k]&&f[i].value>f[j].value)//判断是否合法
				{
					g[i]=max(g[j]+1,g[i]);//动态转移
					if(g[i]>maxx)//取最大值
						maxx=g[i];
				}
	cout<<maxx+1;//因为本身也算一个节点
}

发布了48 篇原创文章 · 获赞 34 · 访问量 4801

Guess you like

Origin blog.csdn.net/dgssl_xhy/article/details/104202077
Recommended