参考网上的一个算法,但是一直都是MLE,实在是想不出来什么办法了。
参考博客:编程之美寻找最近点对
import java.util.Arrays; import java.util.Scanner; public class Main { public static int N=100000; public static int[] list=new int[N]; public static Point[] ptns=new Point[N]; public static float MAX=Float.MAX_VALUE; public static float dis(int i,int j) { return (ptns[i].x-ptns[j].x)*(ptns[i].x-ptns[j].x)+(ptns[i].y-ptns[j].y)*(ptns[i].y-ptns[j].y); } public static float closestPair(int left,int right) { float d=MAX; if(left==right) return d; else if(left+1==right) return dis(left, right); int mid=(left+right)>>1; float d1=closestPair(left, mid); float d2=closestPair(mid+1, right); d=Math.min(d1, d2); int i=0,j=0,k=0; for(i=left;i<=right;i++) { if(Math.abs(ptns[mid].y-ptns[i].y)<d && i!=mid) list[k++]=i; } //对d距离内的点求最近点对 for(i=0;i<k;i++) { for(j=i+1;j<k && Math.abs(ptns[list[j]].x-ptns[list[i]].x)<d;j++) { float dx=dis(list[i], list[j]); if(d>dx) { d=dx; } } } return d; } public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int n=Integer.MAX_VALUE; n=scanner.nextInt(); while(n!=0) { for(int i=0;i<n;i++) { Point point=new Point(); point.x=scanner.nextFloat(); point.y=scanner.nextFloat(); ptns[i]=point; } Arrays.sort(ptns,0,n-1); System.out.println(String.format("%.2f",Math.sqrt(closestPair(0, n-1))/2)); n=scanner.nextInt(); } scanner.close(); } static class Point implements Comparable<Point> { public float x; public float y; @Override public int compareTo(Point o) { // TODO Auto-generated method stub if(this.y>o.y) return 1; else if(this.y<o.y) return -1; else { if(this.x>o.x) return 1; else if(this.x<o.x) return -1; return 0; } } } }
时间: 2024-10-12 12:09:19