4-9 汽车加油问题
问题描述
一辆汽车加满油后可行驶 n 公里。旅途中有若干个加油站。设计一个有效算法,指出应 在哪些加油站停靠加油,使沿途加油次数最少。并证明算法能产生一个最优解。
对于给定的 n 和 k 个加油站位置,编程计算最少加油次数。
第一行有 2 个正整数 n 和 k,表示汽车加满油后可行驶n 公里,且旅途中有 k 个加油站。接下来的 1 行中,有 k+1 个整数,表示第 k 个加油站与第 k-1 个加油站之间的距离。第 0 个加油站表示出发地,汽车已加满油。第 k+1 个加油站表示目的地。
Java
import java.util.Scanner;
public class QiCheJiaYou {
private static int n,k;
private static int[] dist;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while (true){
n = input.nextInt();
k = input.nextInt();
dist = new int[k+1];
for(int i=0; i<=k; i++)
dist[i] = input.nextInt();
int result = greedy();
if(result == -1)
System.out.println("No Solution!");
else
System.out.println(result);
}
}
//最远加油站优先
private static int greedy(){
int count=0,m=dist.length;
for(int j=0; j<m; j++)
if(dist[j] > n)
return -1;
for(int i=0,sum=0; i<m; i++){
sum += dist[i];
if(sum > n){
count++;
sum = dist[i];
}
}
return count;
}
}
Input & Output
7 7
1 2 3 4 5 1 6 6
4
7 7
1 2 3 4 5 1 6 65
No Solution!
Reference
王晓东《计算机算法设计与分析》(第3版)P132