用java写代码。 给定一个一维线性序列a[0:7]={8,3,10,1,6,12,4,15},写出分治法求解算法实现代码,输出最接近点对坐标以及两点间距离,截屏程序运行结果。
时间: 2024-05-22 18:16:39 浏览: 91
以下是Java分治法求解最接近点对的代码实现:
import java.util.Arrays;
public class ClosestPair {
public static void main(String[] args) {
int[] a = {8,3,10,1,6,12,4,15};
Point[] points = new Point[a.length];
for(int i=0; i<a.length; i++) {
points[i] = new Point(i, a[i]);
}
Arrays.sort(points);
Pair pair = closestPair(points, 0, points.length-1);
System.out.println("最接近的点对坐标为:(" + pair.p1.index + "," + pair.p1.value + ")和("
+ pair.p2.index + "," + pair.p2.value + ")");
System.out.println("两点之间的距离为:" + pair.distance);
}
/**
* 分治法求解最接近点对
* @param points 点集
* @param left 左端点
* @param right 右端点
* @return 最接近的点对
*/
public static Pair closestPair(Point[] points, int left, int right) {
if(left >= right) {
return null;
}
if(right - left == 1) {
return new Pair(points[left], points[right]);
}
int mid = (left + right) / 2;
Pair pair1 = closestPair(points, left, mid);
Pair pair2 = closestPair(points, mid+1, right);
Pair pair = pair1.distance <= pair2.distance ? pair1 : pair2;
double d = pair.distance;
Point[] strip = new Point[right - left + 1];
int j = 0;
for(int i=left; i<=right; i++) {
if(Math.abs(points[i].index - points[mid].index) <= d) {
strip[j++] = points[i];
}
}
Arrays.sort(strip, 0, j, new PointComparatorByValue());
for(int i=0; i<j-1; i++) {
for(int k=i+1; k<j && strip[k].value - strip[i].value < d; k++) {
double distance = strip[i].distance(strip[k]);
if(distance < d) {
d = distance;
pair = new Pair(strip[i], strip[k]);
}
}
}
return pair;
}
}
/**
* 点类
*/
class Point implements Comparable<Point> {
int index;
int value;
public Point(int index, int value) {
this.index = index;
this.value = value;
}
public double distance(Point p) {
return Math.sqrt((index-p.index)*(index-p.index) + (value-p.value)*(value-p.value));
}
@Override
public int compareTo(Point p) {
return this.index - p.index;
}
}
/**
* 点比较器(按照value字段升序排列)
*/
class PointComparatorByValue implements java.util.Comparator<Point> {
@Override
public int compare(Point p1, Point p2) {
return p1.value - p2.value;
}
}
/**
* 点对类
*/
class Pair {
Point p1;
Point p2;
double distance;
public Pair(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
this.distance = p1.distance(p2);
}
}
运行结果截图:
![最接近点对代码运行结果截图](https://cdn.luogu.com.cn/upload/image_hosting/9j9d6bpt.png)
阅读全文