题目描述
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
一个人可以从某个点滑向上下左右相邻四个点之一,当且仅当高度会减小。在上面的例子中,一条可行的滑坡为 2424-1717-1616-11(从 2424 开始,在 11 结束)。当然 2525-2424-2323-\ldots…-33-22-11 更长。事实上,这是最长的一条。
输入格式
输入的第一行为表示区域的二维数组的行数 RR 和列数 CC。下面是 RR 行,每行有 CC 个数,代表高度(两个数字之间用 11 个空格间隔)。
输出格式
输出区域中最长滑坡的长度。
输入输出样例
输入 #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
输出 #1复制
25
说明/提示
对于 100\%100% 的数据,1\leq R,C\leq 1001≤R,C≤100。
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
//解题思路:
//dp解法,但要注意去除后效性,得先处理高度低的
template<typename T>
inline void read(T &x)
{
register int f = 1; x = 0;
register char c = getchar();
while(c > '9' || c < '0')
{
if(c == '-') f = -1;
c = getchar();
}
while(c >= '0' && c <= '9')
{
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
x *= f;
}
const int maxn = 1e2 + 5;
int fx[] = {-1, 0, 1, 0}, fy[] = {0, 1, 0, -1};
long long dp[maxn][maxn], mp[maxn][maxn];
struct node
{
int val, x, y;
node(int val, int x, int y)
:x(x), y(y), val(val)
{}
bool operator<(const node &rhs) const
{
return val > rhs.val;
}
};
//使用优先队列,高度低的优先
priority_queue<node> q;
int main()
{
int r, c;
read(r); read(c);
// 读入地图及入队
for(int i = 1; i <= r; i++)
{
for(int j = 1; j <= c; j++)
{
read(mp[i][j]);
q.push(node(mp[i][j], i, j));
}
}
long long ans(0);
while(!q.empty())
{
// 出队则更新相邻点
int i = q.top().x, j = q.top().y;
q.pop();
int x, y;
for(int k = 0; k < 4; k++)
{
x = i + fx[k];
y = j + fy[k];
if(mp[i][j] < mp[x][y] && x >= 1 && x <= r && y >= 1 && y <= c)
{
dp[x][y] = max(dp[x][y], dp[i][j] + 1);
}
}
// 更新最大值
ans = max(dp[i][j], ans);
}
// 本身也是一个长度1,加上端点本身长度
printf("%lld\n", ans + 1);
return 0;
}