Huffman树(贪心)

合并果子

在这里插入图片描述
在这里插入图片描述

import java.io.*;
import java.util.*;

public class Main{
    
    
    public static void main(String[] args)throws IOException{
    
    
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        String[] strs=in.readLine().split(" ");
        int n=Integer.parseInt(strs[0]);
        strs=in.readLine().split(" ");
        Queue<Integer> hf=new PriorityQueue<>();
        for(int i=0;i<n;i++)
            hf.add(Integer.parseInt(strs[i]));
        int sum=0;
        while(hf.size()!=1){
    
    
            int a=hf.poll();
            int b=hf.poll();
            hf.add(a+b);
            sum+=a+b;
        }
        System.out.println(sum);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_54136420/article/details/129727264