POJ 1088----滑雪(DP)
原題連接:http://poj.org/problem?id=1088
Description
Michael喜歡滑雪百這并不奇怪, 因?yàn)榛┑拇_很刺激。可是為了獲得速度,滑的區(qū)域必須向下傾斜,而且當(dāng)你滑到坡底,你不得不再次走上坡或者等待升降機(jī)來(lái)載你。Michael想知道載一個(gè)區(qū)域中最長(zhǎng)底滑坡。區(qū)域由一個(gè)二維數(shù)組給出。數(shù)組的每個(gè)數(shù)字代表點(diǎn)的高度。下面是一個(gè)例子
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一個(gè)人可以從某個(gè)點(diǎn)滑向上下左右相鄰四個(gè)點(diǎn)之一,當(dāng)且僅當(dāng)高度減小。在上面的例子中,一條可滑行的滑坡為24-17-16-1。當(dāng)然25-24-23-…-3-2-1更長(zhǎng)。事實(shí)上,這是最長(zhǎng)的一條。
Input
輸入的第一行表示區(qū)域的行數(shù)R和列數(shù)C(1 <= R,C <= 100)。下面是R行,每行有C個(gè)整數(shù),代表高度h,0<=h<=10000。
Output
輸出最長(zhǎng)區(qū)域的長(zhǎng)度。
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
思路解析:看到數(shù)據(jù)就可以基本判斷這是個(gè)圖論的問題,基本要用的無(wú)非dfs,dp之類的。簡(jiǎn)單分析之后,我們得知是要從圖中找到一條最長(zhǎng)的路徑。我們可以從每個(gè)點(diǎn)出發(fā),進(jìn)行按方向走動(dòng)(即定義dir[][] = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}},四個(gè)坐標(biāo)的順序無(wú)所謂)。如果到某個(gè)點(diǎn)的一條路徑是最長(zhǎng)的,那么它之前的點(diǎn)連起來(lái)一定是最長(zhǎng)的。
import java.util.Scanner;public class Main {static int n, m;static int[][] f, dp;static int max = 0;static int[][] dir = {{0,-1}, {0, 1}, {-1, 0}, {1, 0}};public static void main(String[] args) {Scanner in = new Scanner(System.in);n = in.nextInt();m = in.nextInt();f = new int[n + 1][m + 1];dp = new int[n + 1][m + 1];for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {f[i][j] = in.nextInt();}}for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {max = Math.max(max, dp(i, j) + 1);}}System.out.println(max);}private static int dp(int x, int y) {// TODO Auto-generated method stubint dx, dy;if (dp[x][y] != 0) {return dp[x][y];}for (int i = 0; i < 4; i++) {dx = x + dir[i][0];dy = y + dir[i][1];if (dx < 1 || dy < 1 || dx > n || dy > m || f[dx][dy] > f[x][y]) {continue;}dp[x][y] = Math.max(dp[x][y], dp(dx, dy) + 1);}return dp[x][y];} }總結(jié)
以上是生活随笔為你收集整理的POJ 1088----滑雪(DP)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: T-sql 游标
- 下一篇: RSA不下载批次的问题