赞
踩
import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; public class Demo { // 待实现函数,在此函数中填入答题代码 private static int deliver(int num, int[] communities) { if (communities.length == 0) { return 0; } // 一、人数多于社区数 if (num >= communities.length) { Arrays.sort(communities); return communities[communities.length - 1]; } int max = communities[communities.length - 1]; // 二、人数少于社区数,进行合并 // 用链表 合并 PriorityQueue<Node> nodeQueue = new PriorityQueue<>(Comparator.comparing(node -> node.sumTime)); Node item = new Node(); for (int i = 0; i < communities.length - 1; i++) { int value = communities[i]; Node node = new Node(i, value); if (value > max) { max = value; } item.next = node; item = node; node.sumTime = communities[i] + communities[i + 1]; nodeQueue.add(node); } item.next = new Node(communities.length - 1, communities[communities.length - 1]); int[] merged = new int[communities.length]; for (int i = 0; i < communities.length - num; ) { Node node = nodeQueue.poll(); //已合并,标记nodeQueue中的节点 if (merged[node.index] == 1) { continue; } //合并下一个节点 merged[node.next.index] = 1; node.time = node.sumTime; node.next = node.next.next; if (node.next != null) { //刷新,计算下次合并的大小 node.sumTime = node.sumTime + node.next.time; } //加回到队列中排序 nodeQueue.offer(node); //耗时,取合并后所有节点的最大值 max = Math.max(max, node.time); i++; } return max; } static class Node { int index; int time; //合并下个节点后的大小,用来排序 int sumTime; Node next; public Node(int index, int time) { this.index = index; this.time = time; } public Node() { } } // main入口 public static void main(String[] args) { Scanner cin = new Scanner(System.in, StandardCharsets.UTF_8.name()); int num = cin.nextInt(); int communitiesCnt = cin.nextInt(); int[] communities = new int[communitiesCnt]; for (int i = 0; i < communitiesCnt; i++) { communities[i] = cin.nextInt(); } cin.close(); System.out.println(deliver(num, communities)); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。