第五屆藍橋杯Java B——地宮取寶
X 國王有一個地宮寶庫。是 n x m 個格子的矩陣。每個格子放一件寶貝。每個寶貝貼著價值標籤。
地宮的入口在左上角,出口在右下角。
小明被帶到地宮的入口,國王要求他只能向右或向下行走。
走過某個格子時,如果那個格子中的寶貝價值比小明手中任意寶貝價值都大,小明就可以拿起它(當然,也可以不拿)。
當小明走到出口時,如果他手中的寶貝恰好是k件,則這些寶貝就可以送給小明。
請你幫小明算一算,在給定的局面下,他有多少種不同的行動方案能獲得這k件寶貝。
【資料格式】
輸入一行3個整數,用空格分開:n m k (1<=n,m<=50, 1<=k<=12)
接下來有 n 行資料,每行有 m 個整數 Ci (0<=Ci<=12)代表這個格子上的寶物的價值
要求輸出一個整數,表示正好取k個寶貝的行動方案數。該數字可能很大,輸出它對 1000000007 取模的結果。
例如,輸入:
2 2 2
1 2
2 1
程式應該輸出:
2
再例如,輸入:
2 3 2
1 2 3
2 1 5
程式應該輸出:
14
簡單DP一下就行了
import java.io.BufferedInputStream; import java.util.Scanner; public class Main { static int n, m, k; static int[][] map; static long[][][][] res; static int[][] dr = { { 1, 0 }, { 0, 1 } }; static int MOD = 1000000007; public static void main(String[] args) { Scanner cin = new Scanner(new BufferedInputStream(System.in)); n = cin.nextInt(); m = cin.nextInt(); k = cin.nextInt(); map = new int[n][m]; res = new long[51][51][13][14]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) map[i][j] = cin.nextInt(); System.out.println(dfs(0, 0, 0, -1)); } private static long dfs(int x, int y, int idx, int max) { if (res[x][y][idx][max + 1] != 0) return res[x][y][idx][max + 1]; if (idx > k) return 0; long ans = 0; int cur = map[x][y]; if (x == n - 1 && y == m - 1) { if (idx == k || (idx == k - 1 && cur > max)) return ans = (++ans) % MOD; } else { for (int i = 0; i < 2; i++) { int nx = x + dr[i][0]; int ny = y + dr[i][1]; if (nx < n && ny < m) { if (cur > max) ans += dfs(nx, ny, idx + 1, cur); ans += dfs(nx, ny, idx, max); } } } res[x][y][idx][max + 1] = ans % MOD; return res[x][y][idx][max + 1]; } }