AcWing 149. 【java】荷马史诗
原题链接
简单
作者:
tt2767
,
2019-12-22 00:44:20
,
所有人可见
,
阅读 885
// 最顶层必须要有k个合并才是最优的,不然可以任意一个节点提权后,路径变短,结果变小
// 注意这个heap的比较函数 (a.x > b.x ? 1 : -1) 不知道为什么直接强转int 有问题
import java.util.*;
public class Main{
class Node{
long x;
int y;
Node(long x, int y){
this.x = x;
this.y = y;
}
}
void run(){
int n = jin.nextInt();
int k = jin.nextInt();
for (int i = 0 ; i < n ; i ++) heap.offer(new Node(jin.nextLong(), 0));
solve(n, k);
}
void solve(int n, int k){
while ( (heap.size()-1)%(k-1) != 0) heap.offer(new Node(0, 0));
long res = 0;
while (heap.size() > 1){
long sum = 0;
int depth = 0;
for (int i = 0 ; i < k ; i++){
Node top = heap.poll();
sum += top.x;
depth = Math.max(depth, top.y);
}
heap.add(new Node(sum, depth + 1));
res += sum;
}
// long res = 0;
// while (heap.size() > 1){ // 按视频讲的做法,其实没懂WA在哪了,后面再看吧
// int mod = (n-1) % (k-1);
// int son = mod == 0 ? k : mod;
// long sum = 0;
// int deep = 0;
// for (int i = 0 ; i < son ; i++){
// Node top = heap.poll();
// sum += top.x;
// deep = Math.max(deep, top.y);
// }
// heap.add(new Node(sum, deep + 1));
// res += sum;
// }
System.out.println(res);
System.out.println(heap.peek().y);
}
private Queue<Node> heap = new PriorityQueue<Node>(100002, (a,b) -> (a.x == b.x ? a.y-b.y : (a.x > b.x ? 1 : -1)));
private Scanner jin = new Scanner(System.in);
public static void main(String[] args) throws Exception {new Main().run();}
}
java 的这个compare接口比较坑 如果是 -2e9 -(1e9) 本来 -2e9比1e9小 要返回-1 但是溢出了就变成整数了 就认为-2e9比1e9大
👍