汽车加油问题:java版算法设计与分析
import java.io.*;
class Problem
{
//加油站间距 加油站点 加满油后行驶的路程
public int Greedy(int distance[], int note[], int n)
{ //s--行驶的路程
int i, j, s, add = 0, p = 0, k = distance.length;
for (i = 0; i < k; i++)
{
if (distance[i] > n)
{//不能到达目的地
return -1;
}
}
for (j = 0, s = 0; j < k; j++)
{
s = s+distance[j];
if (s > n)
{//需要加油
add++;
note[p++] = j;
s = distance[j];
}
}
return add;
}
}
public class RefuelCar {
public static void main(String[] args) throws IOException
{
int n,k;
int count=0;//加油次数 www.zzzyk.com
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入汽车加满油后可行驶路程:");
String str=br.readLine();
n=Integer.parseInt(str);
System.out.println("请输入途经加油站总数:");
String str_k=br.readLine();
k=Integer.parseInt(str_k);
int distance[]=new int[k+1];//加油站间距
int note[] = new int[k];//记录加油站点
for(int i=0;i<=k;i++)
{
System.out.println("请输入加油站"+(i)+"到加油站"+(i+1)+"间距");
String temp=br.readLine();
distance[i]=Integer.parseInt(temp.toString());
}
Problem p=new Problem();
count=p.Greedy(distance, note,n);
if (count >= 0)
{
if (count == 0)
System.out.println("汽车不用加油就可到达终点!");
else
{
System.out.println("汽车在旅途中需加"+count+"次油!");
System.out.println("分别在以下加油站加了油:");
for (int i = 0; i < note.length; i++)
{
if (note[i] != 0)
{//输出需加油站点
System.out.println("第" + note[i] + "个加油站!");
}
}
}
}
else
System.out.println("汽车无法到达终点!");
}
}
摘自 spy1403414807的专栏
补充:软件开发 , Java ,