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

题目描述:

输入描述:

输出描述:

示例:

输入:

复制代码
3 5
0 0
1 4
5 6
2 3
7 8
3 -1

输出:

java 复制代码
5 3 -1 4
1 1 4 5
3 2 3 5

题解:Java中可以使用最大堆(通过最小堆模拟)来找到距离最近的k个点:

代码:

java 复制代码
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]);
        }
    }
}
相关推荐
小雨下雨的雨21 分钟前
井字棋AI机器人实现详解 - Minimax算法实战-鸿蒙PC Electron框架完成
前端·人工智能·算法·华为·electron·鸿蒙
xieliyu.3 小时前
Java算法精讲:双指针(三)
java·开发语言·算法
明夜之约3 小时前
Spring Boot 自动装配源码
java·spring boot·后端
Leaton Lee3 小时前
Spring Boot分层架构详解:从Controller到Service再到Mapper的完整流程
java·spring boot·后端·架构
Jinkxs3 小时前
Resilience4j- 与 Spring Boot 快速集成:自动配置与基础注解使用
java·spring boot·后端
辣机小司3 小时前
【踩坑记录:Spring Boot 配置文件读取值不一致?警惕 YAML 的“八进制陷阱”与 SnakeYAML 版本之谜】
java·spring boot·后端·yaml·踩坑记录
fangdengfu1234 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch
云烟成雨TD5 小时前
Spring AI 1.x 系列【51】可观测性技术选型
java·人工智能·spring
星越华夏5 小时前
ESP32-CAM图像传输项目说明文档
java·后端·struts·esp32
Jinkxs5 小时前
Java 跨域14-Java 与区块链(Hyperledger)集成
java·开发语言·区块链