欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > 华为5.7机考第一题充电桩问题Java代码实现

华为5.7机考第一题充电桩问题Java代码实现

2025/5/14 0:49:01 来源:https://blog.csdn.net/2301_81193552/article/details/147811970  浏览:    关键词:华为5.7机考第一题充电桩问题Java代码实现

题目描述:

输入描述:

输出描述:

示例:

输入:

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});// 保持堆的大小不超过kif (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]);}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词