02:滑雪
點擊打開鏈接http://bailian.openjudge.cn/2016acm/02/總時間限制: 1000ms 內存限制: 65536kB
- 描述
- 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。當然25-24-23-...-3-2-1更長。事實上,這是最長的一條。 - 輸入
- 輸入的第一行表示區域的行數R和列數C(1 <= R,C <= 100)。下面是R行,每行有C個整數,代表高度h,0<=h<=10000。
- 輸出
- 輸出最長區域的長度。
- 樣例輸入
-
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
- 樣例輸出
-
25
基本思想:
簡單的dp思想,利用遞歸找到該點可到達的最低點或者最高點,賦值爲1,然後逐步返回,每返回一次選出上下左右最大的步數再+1,這樣該點可到達的區域就全部賦值,然後再遍歷到該點不能到達的地方,再次根據上面的思想賦值,最後選出步數最大的點。
剛開始學比較生疏,只要跟着代碼走一遍就好多了,明白什麼是幹什麼的,祝每一位程序猿技術突飛猛進(包括我),哈哈。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 110;
int High[maxn][maxn]; //地圖高度
int step[maxn][maxn]; //每點的最長步數;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; //四個方向;
int row, column; //地圖的 行, 列;
int dp(int r, int c)
{
if(step[r][c]!=0) //遞歸出口,若該點已經賦值,直接返回;
return step[r][c];
int ans = 0;
for( int i=0; i<4; i++) // 與四個方向比較,選出最大的值;
{
int x = r + dir[i][0];
int y = c + dir[i][1];
if( x>=1 && x<=row && y>=1 && y<=column &&
High[r][c] > High [x][y]) // <號、>號 都可以, 看你要找最低點還是最高點;
ans = max( ans, dp(x, y) ); // 選出最大的值,若該點沒有賦值,接着滑雪嘍。
}
step[r][c] = ans + 1; // 該點比周圍最大點大1;
return step[r][c];
}
int main()
{
while(cin >> row >> column){
// 初始化
int i, j;
for( i=1; i<=row; i++)
for( j=1; j<=column; j++)
cin >> High[i][j]; // 初始化地圖;
memset(step, 0, sizeof(step)); // 初始化步數都爲0;
int max_step=-1; // 最大步數;
for( i=1; i<=row; i++)
{
for( j=1; j<=column; j++)
{
max_step = max(max_step, dp(i, j)); // 在遍歷過程中給步數賦值,並選出最大值;
}
}
cout << max_step <<endl; // 恭喜你滑了世界最長的距離!
}
return 0;
}