POJ 1088 滑雪 (記憶化搜尋)
阿新 • • 發佈:2019-01-31
滑雪
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
一個人可以從某個點滑向上下左右相鄰四個點之一,當且僅當高度減小。在上面的例子中,一條可滑行的滑坡為24-17-16-1。當然25-24-23-...-3-2-1更長。事實上,這是最長的一條。
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Description
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更長。事實上,這是最長的一條。
Input
輸入的第一行表示區域的行數R和列數C(1 <= R,C <= 100)。下面是R行,每行有C個整數,代表高度h,0<=h<=10000。Output
輸出最長區域的長度。Sample Input
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
Sample Output
25
分析:一個記憶化搜尋,算出每個點能到達的最長路徑長度。
滿足 record[i][j] = max{ record[i][j-1], record[i-1][j], record[i][j+1], record[i+1][j] } + 1.
AC程式碼:
#include"string.h" #include"stdio.h" int m,n; int a[110][110]; int record[110][110]; int slide(int i,int j) { int max=0,temp; if(i>m||j>n||i<1||j<1) return 0; if(record[i][j]) return record[i][j]; if(a[i+1][j]<a[i][j]) { temp = slide(i+1,j); if(temp>max) max = temp; } if(a[i-1][j]<a[i][j]) { temp = slide(i-1,j); if(temp>max) max = temp; } if(a[i][j+1]<a[i][j]) { temp = slide(i,j+1); if(temp>max) max = temp; } if(a[i][j-1]<a[i][j]) { temp = slide(i,j-1); if(temp>max) max = temp; } return record[i][j] = max+1; //1是加上本身這個點,到相鄰點長度為1 } int main() { int i,j,max,temp; while(scanf("%d%d",&m,&n)!=EOF) { memset(a,0,sizeof(a)); memset(record,0,sizeof(record)); for(i=1;i<=m;i++) for(j=1;j<=n;j++) scanf("%d",&a[i][j]); max=0; for(i=1;i<=m;i++) //將m*n個點的滑行距離都算 { for(j=1;j<=n;j++) { temp = slide(i,j); if(temp>max) max = temp; } } printf("%d\n",max); } return 0; }