本题借鉴了别人的做题思想,主要如下
第一次提交没有通过,显示Runtime_error,测试了很多数据没有错误,后来吧数组大小改为1000,顺利通过.
1 public class Point implements Comparable<Point> { 2 3 public Point() { 4 // TODO Auto-generated constructor stub 5 6 } 7 8 public double left; 9 public double right; 10 11 private void setLeft(double left) { 12 this.left = left; 13 } 14 15 private void setRight(double right) { 16 this.right = right; 17 } 18 19 @Override 20 public int compareTo(Point o)// 实现接口 21 { 22 if (o != null && o instanceof Point) { 23 Point p = (Point) o; 24 if (left < p.left) 25 return -1; 26 else if (left == p.left) 27 return 0; 28 else 29 return 1; 30 } else 31 return -1; 32 } 33 34 public static void main(String[] args) { 35 // TODO Auto-generated method stub 36 int n, d; // 岛屿个数和雷达侦测距离 37 Point[] poi = new Point[100]; // 存储每个岛屿 38 Scanner sc = new Scanner(System.in); 39 int num = 1; // case个数 40 int[] casenum = new int[100]; // 每个case的所需雷达数 41 n = sc.nextInt(); 42 d = sc.nextInt(); 43 while (n != 0 && d != 0) { 44 boolean legal = true; //判断一个case是否合法,即能否被雷达覆盖 45 int x, y; 46 for (int i = 0; i < n; i++) { 47 x = Integer.parseInt(sc.next()); 48 y = Integer.parseInt(sc.next()); 49 poi[i] = new Point(); 50 // System.out.println(x-Math.sqrt(d*d-y*y)); 51 // double temp1=x-Math.sqrt(d*d-y*y); 52 poi[i].setLeft(x - Math.sqrt(d * d - y * y)); 53 poi[i].setRight(x + Math.sqrt(d * d - y * y)); 54 if (y > d) 55 legal = false; 56 } 57 Arrays.sort(poi, 0, n); //用到了上面重写的compareTO 58 if (!legal) { 59 // System.out.println("Case "+num+": -1"); 60 casenum[num - 1] = -1; 61 num++; 62 } else { 63 double pre = poi[0].right; 64 int radar_num = 1; 65 for (int i = 1; i < n; i++) { 66 if (poi[i].left > pre) { 67 radar_num++; 68 pre = poi[i].right; 69 } else if (poi[i].right < pre) { 70 pre = poi[i].right; 71 } 72 } 73 // System.out.println("Case "+num+": "+radar_num); 74 casenum[num - 1] = radar_num; 75 num++; 76 } 77 n = sc.nextInt(); 78 d = sc.nextInt(); 79 80 } 81 num--; 82 for (int i = 0; i < num; i++) { 83 int j = i + 1; 84 System.out.println("Case " + j + ": " + casenum[i]); 85 } 86 87 } 88 89 }