【蓝桥杯算法】分布式队列【模拟】【2026/04/01】使用优先队列+懒加载

image

image

image

image

首先这道题有两个需要学习的点:
1.这道题没有给输入多少行,只有当输入为空时自己判断去停止输入。
while(sc.hasNextLine())来解决这个问题
同时需要注意如果使用nextLine()之前使用过nextInt(),需要用nextLine()先去除下一行的这个符号。
2.我们需要维护一个优先队列,来保证能实时获取最小值,同时懒加载判断优先队列里的值是否有效。


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        sc.nextLine();
        int[] arr=new int[n];
        PriorityQueue<int[]> queue=new PriorityQueue<>((o1, o2) -> o1[1]-o2[1]);
        for (int i = 1; i < n; i++) {
            queue.add(new int[]{i,0});
        }
        //优先队列(小顶堆)+延迟删
        while(sc.hasNextLine()){
            String line=sc.nextLine().trim();
//            if(line.isEmpty())break;
            String[] parts = line.split("\\s+");
            String ops=parts[0];
            if("add".equals(ops)){
                arr[0]++;
            }
            else if("sync".equals(ops)){
                int i=Integer.parseInt(parts[1]);
                if(arr[i]<arr[0]) arr[i]++;
                queue.add(new int[]{i,arr[i]});
            }
            else{
                while(!queue.isEmpty()){
                    int[] temp=queue.peek();
                    if(arr[temp[0]]==temp[1]){
                        System.out.println(temp[1]);
                        break;
                    }else{
                        queue.poll();
                    }
                }
            }
        }


    }


}
posted @ 2026-04-01 14:57  Jwwind  阅读(4)  评论(0)    收藏  举报