import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int n = scanner.nextInt(); // 数组初始大小
            int k = scanner.nextInt(); // 操作次数

            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = scanner.nextInt(); // 输入数组
            }

            PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); // 使用优先队列,存储数组元素,按降序排列

            for (int i = 0; i < n; i++) {
                pq.offer(arr[i]); // 将数组元素添加到优先队列
            }

            while (k > 0) {
                int max = pq.poll(); // 取出当前优先队列中的最大元素
                pq.offer(max / 2); // 将最大元素的一半加回优先队列
                k--; // 操作次数减1
            }

            List<Integer> result = new ArrayList<>(pq);
            Collections.sort(result); // 将结果排序,以满足字典序要求

            for (int i = 0; i < n - k; i++) {
                System.out.print(result.get(i) + ' '); // 输出结果数组
            }
            System.out.println(); // 换行
        }
        scanner.close();
    }
}
Java算法:数组字典序最大化

原文地址: https://www.cveoy.top/t/topic/bcB7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录