A bus moves along the coordinate line Ox from the point x = 0 to the point x = a. After starting from the point x = 0, it reaches the pointx = a, immediately turns back and then moves to the point x = 0. After returning to the point x = 0 it immediately goes back to the pointx = a and so on. Thus, the bus moves from x = 0 to x = a and back. Moving from the point x = 0 to x = a or from the point x = a to x = 0is called a bus journey. In total, the bus must make k journeys.
The petrol tank of the bus can hold b liters of gasoline. To pass a single unit of distance the bus needs to spend exactly one liter of gasoline. The bus starts its first journey with a full petrol tank.
There is a gas station in point x = f. This point is between points x = 0 and x = a. There are no other gas stations on the bus route. While passing by a gas station in either direction the bus can stop and completely refuel its tank. Thus, after stopping to refuel the tank will contain b liters of gasoline.
What is the minimum number of times the bus needs to refuel at the point x = f to make k journeys? The first journey starts in the pointx = 0.
The first line contains four integers a, b, f, k (0 < f < a ≤ 106, 1 ≤ b ≤ 109, 1 ≤ k ≤ 104) — the endpoint of the first bus journey, the capacity of the fuel tank of the bus, the point where the gas station is located, and the required number of journeys.
Print the minimum number of times the bus needs to refuel to make k journeys. If it is impossible for the bus to make k journeys, print-1.
6 9 2 4
4
6 10 2 4
2
6 5 4 3
-1
题意:在数轴上有一个a点,在0点和a点之间有一个f点为加油站(汽油每次可以加到b),汽车从0到a或者从a到0算一次旅行,汽车一开始在0点,汽油为b,求k次旅行最少加油次数,无法满足k次旅行则输出-1.
思路:把点之间的距离变换为数组。
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int a,b,f,k;
int dis[100005];
int main()
{
scanf("%d%d%d%d",&a,&b,&f,&k);
int curpos=0,curgas=b,curg=0;
int ans=0;
dis[0]=f; //第一段距离,0点到加油站
for(int i=1;i<k;i++) //中间距离,加油站到加油站
{
if(i%2)
{
dis[i]=2*(a-f);
}
else
{
dis[i]=2*f;
}
}
if(k%2) //最后一段距离,加油站到终点
{
dis[k]=a-f;
}
else
{
dis[k]=f;
}
for(int i=0;i<=k;i++)
{
if(curgas<dis[i]) //无法到达下一个点则退出
{
ans=-1;
break;
}
if(i<k&&dis[i]+dis[i+1]>curgas) //到下一个加油站需要加油
{
curgas=b;
ans++;
}
else if(i<k&&dis[i]+dis[i+1]<=curgas) //到下一个加油站不需要加油
{
curgas-=dis[i];
}
}
printf("%d\n",ans);
}