洛谷:P1434【滑雪】
阿新 • • 發佈:2018-12-14
題目描述
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(從24開始,在1結束)。當然25-24-23―┅―3―2―1更長。事實上,這是最長的一條。
輸入輸出格式
輸入格式:
輸入的第一行為表示區域的二維陣列的行數R和列數C(1≤R,C≤100)。下面是R行,每行有C個數,代表高度(兩個數字之間用1個空格間隔)。
輸出格式:
輸出區域中最長滑坡的長度。
很明顯,這題用動態規劃是比較難做的,所以我們可以考慮dfs,對每個點都搜出它可以經過的最大高度,然後求出每個點的最大值。於是就有了程式碼:
#include<bits/stdc++.h> using namespace std; #define mmax 0x3f3f3f #define maxrc 100 + 5 const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int mmap[maxrc][maxrc]; int dp[maxrc][maxrc]; int r, c; bool check(int x, int y){ return 0 < x && x <= r && 0 < y && y <= c; } int dfs(int x, int y){ for(int i = 0; i < 4; i++){ int tx = x + dir[i][0]; int ty = y + dir[i][1]; if(check(tx, ty) && mmap[tx][ty] > mmap[x][y]){ dp[x][y] = max(dfs(tx, ty) + 1, dp[x][y]); } } if(!dp[x][y]) dp[x][y] = 1; return dp[x][y]; } int main(void){ cin >> r >> c; for(int i = 1; i <= r; i++){ for(int j = 1; j <= c; j++){ cin >> mmap[i][j]; } } dp[1][1] = 1; int tmp = -mmax; for(int i = 1; i <= r; i++){ for(int j = 1; j <= c; j++){ tmp = max(dfs(i, j), tmp); } } printf("%d\n", tmp); return 0; }
然後你就得了90分~。所以我們需要記憶化搜尋:
#include<bits/stdc++.h> using namespace std; #define mmax 0x3f3f3f #define maxrc 100 + 5 const int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int mmap[maxrc][maxrc]; int dp[maxrc][maxrc]; int r, c; bool check(int x, int y){ return 0 < x && x <= r && 0 < y && y <= c; } int dfs(int x, int y){ if(dp[x][y] && (x != 1 && y != 1)) return dp[x][y]; for(int i = 0; i < 4; i++){ int tx = x + dir[i][0]; int ty = y + dir[i][1]; if(check(tx, ty) && mmap[tx][ty] > mmap[x][y]){ dp[x][y] = max(dfs(tx, ty) + 1, dp[x][y]); } } if(!dp[x][y]) dp[x][y] = 1; return dp[x][y]; } int main(void){ cin >> r >> c; for(int i = 1; i <= r; i++){ for(int j = 1; j <= c; j++){ cin >> mmap[i][j]; } } dp[1][1] = 1; int tmp = -mmax; for(int i = 1; i <= r; i++){ for(int j = 1; j <= c; j++){ tmp = max(dfs(i, j), tmp); } } printf("%d\n", tmp); return 0; }
美滋滋~