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 問題分析 假設已經實現函數:int find(int x,int y)返回從點(x,y)的最長坡道的長度,那么我們只需要遍歷題目給出的數組,計算長度取最大值即為最終答案。 函數實現: 我們利用temp[i][j]數組判斷是否已經計算過當前點(i,j)避免重復計算,這樣能夠節省時間。如果已經計算過當前節點直接返回temp[i][j]中存儲的值。 接著調用find函數計算上下左右四個節點中滿足條件的節點,并取最大值max。 返回max加1。 代碼實現
#include<iostream>#include<cstdio>#include<algorithm>using namespace std;int array[101][101];int temp[101][101];int find(int x,int y,int R,int C){ int maxi=0; if(temp[x][y]!=1)return temp[x][y]; if(y-1>=0&&array[x][y]>array[x][y-1])maxi=max(maxi,temp[x][y-1]=find(x,y-1,R,C)); if(x-1>=0&&array[x][y]>array[x-1][y])maxi=max(maxi,temp[x-1][y]=find(x-1,y,R,C)); if(y+1<C&&array[x][y]>array[x][y+1])maxi=max(maxi,temp[x][y+1]=find(x,y+1,R,C)); if(x+1<R&&array[x][y]>array[x+1][y])maxi=max(maxi,temp[x+1][y]=find(x+1,y,R,C)); return maxi+1;}int main(){ int R,C; while(scanf("%d %d",&R,&C)==2){ for(int i=0;i<R;i++) for(int j=0;j<C;j++){ scanf("%d",&array[i][j]); temp[i][j]=1; } int maxi=0; for(int i=0;i<R;i++) for(int j=0;j<C;j++) maxi=max(maxi,find(i,j,R,C));新聞熱點
疑難解答