题意:
有个小偷,为了躲避警察的追捕,决定每天乘坐一次航班来甩掉警察,总共有个n个城市,城市 i 到城市 j 每天到航班的价格都不同(价格0表示当前没有航班)。
总共需要乘坐 k 次航班,并且最后一次航班到达目的地 N,问最小的航班花费是多少。
解题思路:
抛弃一切条件,只要思考一个事,第 i 天 到达第j个城市的最小花费是多少,答案就是dp[k][n]。
在第i天计算城市j的花费,需要计算i-1天所有其他城市的花费。那么dp[i][j] = min(dp[i-1][t]) {t!=j && 城市 t 在当天有航班到 j 城市 }
注意:初始化条件是dp[0][1] = 0,其他都是-1,表示不存在方案。
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Main { static final int N = 13; static final int K = 1003; static final int D = 32; // static final int N = 4; // static final int K = 7; // static final int D = 8; static int dp[][] = new int[K][N]; static int num[][][] = new int[N][N][D]; static int ds[][] = new int[N][N]; static int n; static int k; static int cases; public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(System.in); //Scanner scanner = new Scanner(new File("/Users/caicai/in")); while (true) { n = scanner.nextInt(); k = scanner.nextInt(); if (n == 0 && k == 0) break; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i == j) { j++; } if (j > n) { break; } int d = scanner.nextInt(); ds[i][j] = d; for (int di = 0; di < d; di++) { num[i][j][di] = scanner.nextInt(); } } } // init dp initdp(); ++cases; dp(); } } static void initdp() { for (int i = 0; i < K; i++) { for (int j = 0; j < N; j++) { dp[i][j] = -1; } } } static void dp() { // init dp[0][1] = 0; // dij 第i天第j城市的最小花费 for (int i = 1; i <= k; i++) { for (int e = 1; e <= n; e++) { int maxVal = 0x7fffffff; for (int s = 1; s <= n; s++) { if (e == s) { // the same city continue; } if (dp[i - 1][s] == -1) { // not start continue; } // e is j // s is t int curd = (i - 1) % ds[s][e]; int cost = num[s][e][curd]; if (cost == 0) continue; int val = dp[i - 1][s] + cost; if (maxVal > val) maxVal = val; } if (maxVal != 0x7fffffff) dp[i][e] = maxVal; } } int val = dp[k][n]; System.out.println("Scenario #" + cases); if (val == -1) System.out.println("No flight possible."); else System.out.println("The best flight costs " + val + "."); System.out.println(); } }
原文:https://www.cnblogs.com/shuiyonglewodezzzzz/p/11310912.html