思路:
对所求问题进行一个对偶转换:不是直接计算在一定时间内到达的最少跳过次数,而是跳过若干次之后最短到达时间,就方便使用动态规划了:dp[i][j]表示共计跳了j次通过前i条道路所花费的最小时间。还需要注意浮点数的精度问题:ceil运算之前需要先减一个eps;比较大小的时候也需要加一个eps。
实现:
1 class Solution 2 { 3 public: 4 int minSkips(vector<int>& dist, int speed, int hoursBefore) 5 { 6 int n = dist.size(); 7 double eps = 1e-8; 8 vector<vector<double>> dp(n, vector<double>(n, 0x3f3f3f3f)); 9 dp[0][0] = (double)dist[0] / speed; 10 for (int i = 1; i < n; i++) 11 { 12 dp[i][0] = ceil(dp[i - 1][0] - eps) + (double)dist[i] / speed; 13 for (int j = 1; j <= i; j++) 14 { 15 dp[i][j] = min(ceil(dp[i - 1][j] - eps) + (double)dist[i] / speed, dp[i - 1][j - 1] + (double)dist[i] / speed); 16 } 17 } 18 int res = -1; 19 for (int i = n - 1; i >= 0; i--) 20 { 21 if (dp[n - 1][i] <= hoursBefore + eps) res = i; 22 } 23 return res; 24 } 25 };