问题描述
V先生有一天工作到很晚,回家的时候要穿过一条长l的笔直的街道,这条街道上有n个路灯。假设这条街起点为0,终点为l,第i个路灯坐标为ai。路灯发光能力以正数d来衡量,其中d表示路灯能够照亮的街道上的点与路灯的最远距离,所有路灯发光能力相同。为了让V先生看清回家的路,路灯必须照亮整条街道,又为了节省电力希望找到最小的d是多少?
输入输入两行数据,第一行是两个整数:路灯数目n (1≤n≤1000),街道长度l (1 ≤l≤109)。第二行有n个整数ai (0 ≤ ai≤ l),表示路灯坐标,多个路灯可以在同一个点,也可以安放在终点位置。 | 输入样例7 15 15 5 3 7 9 14 0 |
输出输出能够照亮整个街道的最小d,保留两位小数。 | 输出样例2.50 |
思路
接收输入后,将各个路灯的位置排序。
考虑三个值:
- 相邻路灯之间间距的最大值(需要除以2之后与后面两者进行比较,或与后两者乘2之后进行比较)
- 最开始的路灯与路的起点的距离
- 最后的路灯与路的尽头的距离
代码
import java.util.*;
public class StreetLamp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//获取路灯数量和 路的长度
String line1 = sc.nextLine();
String[] strs1 = line1.split("\\s+");
int lampNum = Integer.parseInt(strs1[0]);
int streetLen = Integer.parseInt(strs1[1]);
//获取每个路灯的位置:0-streetLen
String line2 = sc.nextLine();
String[] strs2 = line2.split("\\s+");
ArrayList<Integer> intList = new ArrayList<Integer>();
for(int j = 0; j<lampNum; j++) {
intList.add(Integer.parseInt(strs2[j]));
}
Collections.sort(intList);
int minPos = intList.get(0);
int maxPos = intList.get(lampNum-1);
int largestGap = 0;
//找到路灯间的最大间距
for(int i = 1; i<lampNum; i++) {
int gap = intList.get(i)-intList.get(i-1);
largestGap = (gap>largestGap)?gap:largestGap;
}
largestGap = (minPos*2>largestGap)?minPos*2:largestGap;
largestGap = ((streetLen-maxPos)*2>largestGap)?(streetLen-maxPos)*2:largestGap;
double result = largestGap/2.0;
System.out.printf("%.2f",result);
sc.close();
}
参考答案
import java.util.*;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int len = sc.nextInt();
int[] spot = new int[n];
for(int i=0;i<n;i++)
spot[i] = sc.nextInt();
Arrays.sort(spot);
double maxdistance = Double.MIN_VALUE;
for(int i=1;i<n;i++){
if(spot[i]-spot[i-1]>maxdistance)
maxdistance = spot[i]-spot[i-1];
}
double left = spot[0];
double right = len - spot[n-1];
if(left>right&&left>maxdistance/2){
System.out.printf("%.2f",left);
}
else if(right>=left&&right>maxdistance/2){
System.out.printf("%.2f",right);
}
else{
System.out.printf("%.2f",maxdistance/2);
}
}
}
问题
跟别人的代码一对比,发现我的代码在接收输入的方面有些繁琐。
还有就是忘记了,第一个路灯与路起点的距离就是照射距离,要比较的话,灯之间的距离需要除以2再比较。