試題 基礎(chǔ)練習 Huffuman樹(Java)
資源限制
時間限制:1.0s 內(nèi)存限制:512.0MB
問題描述
Huffman樹在編碼中有著廣泛的應用。在這里,我們只關(guān)心Huffman樹的構(gòu)造過程。 給出一列數(shù){pi}={p0, p1, …, pn-1},用這列數(shù)構(gòu)造Huffman樹的過程如下: 1. 找到{pi}中最小的兩個數(shù),設(shè)為pa和pb,將pa和pb從{pi}中刪除掉,然后將它們的和加入到{pi}中。這個過程的費用記為pa + pb。 2. 重復步驟1,直到{pi
輸入格式
輸入的第一行包含一個正整數(shù)n(n<=100)。 接下來是n個正整數(shù),表示p0, p1, …, pn-1,每個數(shù)不超過1000。
輸出格式
輸出用這些數(shù)構(gòu)造Huffman樹的總費用。
樣例輸入
5 5 3 8 2 9
樣例輸出
59
代碼
1 import java.util.Collections; 2 import java.util.PriorityQueue; 3 import java.util.Scanner; 4 import java.util.Vector; 5 ? 6 ? 7 public class Main { 8 static PriorityQueue<Integer> q; 9 10 public static void main(String[] args) { 11 Scanner sc = new Scanner(System.in); 12 q = new PriorityQueue<Integer>(); 13 int n = sc.nextInt(); 14 for (int i = 0; i < n; i++) { 15 q.offer(sc.nextInt()); 16 } 17 int ans = 0; 18 int tmp1, tmp2; 19 int ans1 = 0; 20 while (!q.isEmpty() && q.size() >= 2) { 21 ans = 0; 22 tmp1 = q.poll(); 23 tmp2 = q.poll(); 24 ans = tmp1 + tmp2; 25 q.offer(ans); 26 ans1 += ans; 27 } 28 System.out.println(ans1); 29 } 30 ? 31 } 32 ?
總結(jié)
1.優(yōu)先隊列類——PriorityQueue
(1)初始化
PriorityQueue()//創(chuàng)建一個 PriorityQueue,并根據(jù)其自然順序?qū)υ剡M行排序。
(2)常用函數(shù)
1 add(E e)//將指定的元素插入此優(yōu)先級隊列。 2 clear()//清空 3 contains(Object o) // 如果包含指定元素返回true 4 iterator()//返回在此隊列中的元素上進行迭代的迭代器。 5 offer(E e) // 將指定元素插入此優(yōu)先隊列 6 peek() // 獲取第一個元素,及最小或最大元素 7 poll() // 獲取并移除第一個 8 remove(Object o) // 移除指定元素 9 size() // 返回元素個數(shù)
(3)實現(xiàn)大根堆的兩種方式
java默認的PriorityQueue()是小根堆,也就是按照遞增的順序,那我們想要遞減時怎么辦呢?有兩種方法
1.使用自定義比較器
1 PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(11, new Comparator<Integer>() {//默認初始大小為11 2 public int compare(Integer o1, Integer o2) { 3 return o2-o1; 4 } 5 });
2.將所有數(shù)據(jù)變?yōu)樨摂?shù)再插入
2.算法思想
浙公網(wǎng)安備 33010602011771號