Greedy Algorithm 3-Gas Station Problem

A car can run n kilometers after being filled with gas. There are several gas stations during the journey, and the number of refueling on the way is reduced. An algorithm is designed to output the best refueling plan.

For example, suppose there are 9 gas stations along the route, the total distance is 100 kilometers, and the maximum distance of the car after filling up the gas is 20 kilometers. The position of the car to refuel is shown in the picture.


In order to reduce the frequency of refueling on the way, the car needs to travel as far as possible after refueling once, and then refueling the next time. According to this design idea, formulate the following greedy selection strategy:

(1) When the first time the car departs from the starting point and runs to n=20 kilometers, choose a gas station xi closest to the end point, and choose a gas station 20 kilometers away from the starting point, that is, the second gas station to refuel.
(2) After refueling, the car is in a full fuel state, which is consistent with the state before the car starts. In this way, the problem is reduced to a smaller sub-problem that finds the least number of refueling times for the car from xi to the end.
Continue to solve the sub-problem according to the above strategy, that is, find the nearest gas station n kilometers from the last selected gas station to refuel each time.

In the specific program design, an array x is set to store the distance between the gas station and the starting point. The length of the whole journey is represented by S, the selected gas station is stored by the array a, and total represents the longest journey that has been traversed.


#include <iostream>
#define S 100							/*S:全程长度*/
void main()
	int i, j, n, k = 0, total, dist;
	int x[] = { 10,20,35,40,50,65,75,85,100 };	/*数组x:加油站位置(距离起点的位置)*/
	int a[10];								/*数组a:选择加油点的位置*/
	n = sizeof(x) / sizeof(x[0]);				/*n:沿途加油站的个数*/
	scanf("%d", &dist);
	total = dist;							/*total:总共行使的公里数*/
	j = 1;								/*j:选择的加油站个数*/
	while (total < S)						/*如果汽车未走完全程*/
		for (i = k; i < n; i++)
			if (x[i] > total)				/*如果距离下一个加油站太远*/
				a[j] = x[i - 1];			/*则在当前加油点加油*/
				total = x[i - 1] + dist;		/*计算加完油后能行使的最远距离*/
				k = i;					/*k:记录下一次加油的开始位置*/
				break;					/*退出for循环*/
	printf("行驶%d公里应该选择的加油点:\n", S);
	for (i = 1; i < j; i++)					/*输出选择的加油点*/
		printf("%4d", a[i]);




Guess you like