题目描述:
输入描述:
输出描述:
示例:
输入:
3 5
0 0
1 4
5 6
2 3
7 8
3 -1
输出:
5 3 -1 4
1 1 4 5
3 2 3 5
题解:Java中可以使用最大堆(通过最小堆模拟)来找到距离最近的k个点:
代码:
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] data = br.readLine().split(" ");
int k = Integer.parseInt(data[0]);
int n = Integer.parseInt(data[1]);
int carX = Integer.parseInt(data[2]);
int carY = Integer.parseInt(data[3]);
// 边界条件
if (k == 0 || k > n) {
System.out.println("null");
return;
}
// 使用优先队列模拟最大堆,存储(-distance, -id, x, y)
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> {
if (a[0] != b[0]) return a[0] - b[0]; // 按-distance升序(相当于distance降序)
else return a[1] - b[1]; // 然后按-id升序
});
int idx = 4;
for (int i = 1; i <= n; i++) {
int x = Integer.parseInt(data[idx++]);
int y = Integer.parseInt(data[idx++]);
int d = Math.abs(carX - x) + Math.abs(carY - y);
// 将元素加入堆(使用负值模拟最大堆)
heap.offer(new int[]{-d, -i, x, y});
// 保持堆的大小不超过k
if (heap.size() > k) {
heap.poll();
}
}
// 提取结果并排序
List<int[]> result = new ArrayList<>();
while (!heap.isEmpty()) {
int[] item = heap.poll();
result.add(new int[]{-item[0], -item[1], item[2], item[3]});
}
// 按距离升序、编号升序排序
result.sort((a, b) -> {
if (a[0] != b[0]) return a[0] - b[0];
else return a[1] - b[1];
});
// 输出结果
for (int[] item : result) {
System.out.println(item[1] + " " + item[2] + " " + item[3] + " " + item[0]);
}
}
}