其他分享
首页 > 其他分享> > 考研机试 25.最小花费

考研机试 25.最小花费

作者:互联网

 

时间:2021/03/06

 

一.题目描述

在某条线路上有N个火车站,有三种距离的路程,L1,L2,L3,对应的价格为C1,C2,C3.其对应关系如下: 距离s           票价 0<S<=L1         C1 L1<S<=L2        C2 L2<S<=L3        C3 输入保证0<L1<L2<L3<10^9,0<C1<C2<C3<10^9。 每两个站之间的距离不超过L3。 当乘客要移动的两个站的距离大于L3的时候,可以选择从中间一个站下车,然后买票再上车,所以乘客整个过程中至少会买两张票。 现在给你一个 L1,L2,L3,C1,C2,C3。然后是A B的值,其分别为乘客旅程的起始站和终点站。 然后输入N,N为该线路上的总的火车站数目,然后输入N-1个整数,分别代表从该线路上的第一个站,到第2个站,第3个站,……,第N个站的距离。 根据输入,输出乘客从A到B站的最小花费。

输入描述

以如下格式输入数据:
L1  L2  L3  C1  C2  C3
A  B
N
a[2]
a[3]
……
a[N]

输出描述

可能有多组测试数据,对于每一组数据,
根据输入,输出乘客从A到B站的最小花费。

题目链接

https://www.nowcoder.com/practice/e6df3e3005e34e2598b9b565cfe797c9?tpId=40&tqId=21354&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan%2Fquestion-ranking&tab=answerKey

 

二.算法

题解

对于动态规划问题需要辅助数组和循环,该题是遍历每一个节点,从初始节点开始遍历来寻找l3距离内的最小花费,直到结束节点位置。

代码

import java.util.Scanner;
import java.util.Arrays;

public class Main{
    
    public static void main(String[] args){
        
        Scanner in = new Scanner(System.in);
        
        while(in.hasNext()){
            //读取输入
            int l1 = in.nextInt();
            int l2 = in.nextInt();
            int l3 = in.nextInt();
            int c1 = in.nextInt();
            int c2 = in.nextInt();
            int c3 = in.nextInt();
            int a = in.nextInt();
            int b = in.nextInt();
            int n = in.nextInt();
            int[] counts = new int[n + 1];
            
            for(int i= 2; i <= n; i++){
                counts[i] = in.nextInt();
            }
            
            //初始化辅助数组
            int[] dp = new int[n + 1];
            Arrays.fill(dp, Integer.MAX_VALUE);
            dp[a] = 0;
            
            //求最小花费
            for(int i = a + 1; i <= b; i++){
                for(int j = a; j < i; j++){
                    int length = counts[i] - counts[j];
                    if(length <= l3){
                        int value = (length <= l1 ? c1 : (length <= l2 ? c2 : c3));
                        dp[i] = Math.min(dp[i], dp[j] + value);
                    }
                }
            }
            
            System.out.println(dp[b]);
        }
    }
}

 

标签:25,Scanner,2Fta%,int,nextInt,机试,节点,输入,考研
来源: https://www.cnblogs.com/machi12/p/14489738.html