矩形滑雪場-DP

david喜歡滑雪。他來到了一個滑雪場,這個滑雪場是一個矩形,爲了簡便,我們用r行c列的矩陣來表示每塊地形。爲了得到更快的速度,滑行的路線必須向下傾斜。 例如樣例中的那個矩形,可以從某個點滑向上下左右四個相鄰的點之一。例如24-17-16-1,其實25-24-23…3-2-1更長,事實上這是最長的一條。

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行: 兩個數字r,c(1< =r,c< =100),表示矩陣的行列。 第2..r+1行:每行c個數,表示這個矩陣。

輸出格式:

僅一行: 輸出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

樣例輸出

25


代碼:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>


using namespace std; 
int r,c;


struct Route // 定義一個結構體來存放每個點的位置信息以及高度 
{
int hang;
int lie;
int h;
}route[11025]; // 轉化爲一維數組,用來實現從小到大排序 


int maxLen = 0; // 用來存放最大結果 
int s[105][105]; // 存放原始數據,即原始矩形,s[i][j]表示第i行第j列的高度 
int dp[105][105]; // dp[i][j]表示從點(i,j)出發的最長距離 


int cmp(const void *a, const void *b) // 按從小到大排序
{
struct Route r1 = *(struct Route *)a;
struct Route r2 = *(struct Route *)b;
return r1.h - r2.h;  
}


int main(int argc, char** argv) {
int num = 1;
cin >> r >> c;
for(int i=1; i<=r; i++)
for(int j=1; j<=c; j++)

cin >> route[num].h;
route[num].hang = i;
route[num].lie = j;
s[i][j] = route[num].h;
dp[i][j] = 1; // 每點至少有該點本身 
num++;
}  
qsort(route+1,r*c,sizeof(struct Route),cmp);
for(int k=1; k<=r*c; k++)
{  
if(route[k].lie-1>0 && route[k].h > s[route[k].hang][route[k].lie-1]) // 左邊有點且該點比左邊點高;用原始矩陣s可以方便找到對應的位置即高 
dp[route[k].hang][route[k].lie] = max(dp[route[k].hang][route[k].lie],dp[route[k].hang][route[k].lie-1]+1);
if(route[k].lie+1<=c && route[k].h > s[route[k].hang][route[k].lie+1]) // 與上邊左邊點同理 
dp[route[k].hang][route[k].lie] = max(dp[route[k].hang][route[k].lie],dp[route[k].hang][route[k].lie+1]+1); 
if(route[k].hang-1>0 && route[k].h > s[route[k].hang-1][route[k].lie]) // 上邊有點,且該點比左邊點高
dp[route[k].hang][route[k].lie] = max(dp[route[k].hang][route[k].lie],dp[route[k].hang-1][route[k].lie]+1); 
if(route[k].hang+1<=r && route[k].h > s[route[k].hang+1][route[k].lie]) // 下邊有點且該點比左邊點高
dp[route[k].hang][route[k].lie] = max(dp[route[k].hang][route[k].lie],dp[route[k].hang+1][route[k].lie]+1); 
if(dp[route[k].hang][route[k].lie] > maxLen)
maxLen = dp[route[k].hang][route[k].lie];
}
cout << maxLen << endl;
return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章