题目链接
蜗牛
个人思路
在每根竹竿都求出到达其底部和到达当前竹竿传送门入口的最小耗时,依次递推,求出最后一根竹竿底部的耗时。
参考代码
C++
由于此处需要格式化输出小数点后两位,所以采用printf感觉更方便一些。
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
typedef long long ll;
int n, arr[N],brr[N][2];
double f[N][2];int main()
{ios::sync_with_stdio(0), cin.tie(0);cin >> n;int i, j;for(i = 1; i <= n; ++i) cin >> arr[i];for(i = 1; i < n; ++i) cin >> brr[i][0] >> brr[i + 1][1];// 传输起点和传输终点f[1][0] = arr[1];f[1][1] = arr[1] + brr[1][0] / 0.7;for(i = 2; i <= n; ++i){// 由前一个根爬过来或者从当前竹竿传送出口爬过来f[i][0] = min(f[i - 1][0] + arr[i] - arr[i - 1], f[i - 1][1] + brr[i][1] / 1.3);// 由当前竹竿根爬过来或者从当前竹竿传送出口爬过来if(brr[i][1] > brr[i][0]) f[i][1] = min(f[i][0] + brr[i][0] / 0.7, f[i - 1][1] + (brr[i][1] - brr[i][0]) / 1.3);else f[i][1] = min(f[i][0] + brr[i][0] / 0.7, f[i - 1][1] + (brr[i][0] - brr[i][1]) / 0.7);}// for(i = 1; i <= n; ++i)// {// printf("%lf, %lf\n", f[i][0], f[i][1]);// }printf("%.2lf", f[n][0]);
}
Java
import java.io.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner();int n = sc.nextInt();int[] arr = new int[n + 1];for (int i = 1; i <= n; i++) {arr[i] = sc.nextInt();}int[][] edge = new int[n + 1][2];for (int i = 1; i <= n - 1; ++i) {edge[i][0] = sc.nextInt();edge[i + 1][1] = sc.nextInt();}double[][] dp = new double[n + 1][2];// 初始化到第一根棍子时间dp[1][0] = arr[1];dp[1][1] = dp[1][0] + edge[1][0] / 0.7;for (int i = 2; i <= n; ++i) {dp[i][0] = Math.min(dp[i - 1][0] + arr[i] - arr[i - 1], dp[i - 1][1] + edge[i][1] / 1.3);if (edge[i][0] > edge[i][1]) {// 需要往上爬dp[i][1] = Math.min(dp[i - 1][0] + arr[i] - arr[i - 1] + edge[i][0] / 0.7, dp[i - 1][1] + (edge[i][0] - edge[i][1]) / 0.7);} else {dp[i][1] = Math.min(dp[i - 1][0] + arr[i] - arr[i - 1] + edge[i][0] / 0.7, dp[i - 1][1] + (edge[i][1] - edge[i][0]) / 1.3);}}System.out.printf("%.2f", dp[n][0]);}
}
class Scanner {static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));public int nextInt() {try {st.nextToken();} catch (IOException e) {throw new RuntimeException(e);}return (int) st.nval;}
}