华为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]);
        }
    }
}
相关推荐
Java中文社群29 分钟前
超实用!Dify快速接入本地MCP服务
java·人工智能·后端
RainbowSea1 小时前
6-2 MySQL 数据结构选择的合理性
java·后端·mysql
androidwork1 小时前
Fragment事务commit与commitNow区别
android·java·kotlin
WispX8881 小时前
【手写系列】手写 AQS 实现 MyLock
java·开发语言·并发·aqs··手写·lock
初叶 crmeb1 小时前
JAVA单商户易联云小票打印替换模板
java·linux·python
RainbowSea2 小时前
秒杀/高并发解决方案+落地实现 (技术栈: SpringBoot+Mysql + Redis +RabbitMQ +MyBatis-Plus +Maven-5
java·spring boot·分布式
汤姆yu2 小时前
基于springboot的民间文化艺术品销售系统
java·spring boot·后端
二进制小甜豆2 小时前
Spring MVC
java·后端·spring·mvc
Yvonne9782 小时前
定时任务:springboot集成xxl-job-core(一)
java·spring boot·xxl-job
嘿嘿-g2 小时前
华为IP(7)
网络·华为