4-20 多元Huffman编码变形
问题描述
在一个操场的四周摆放着 n 堆石子。现要将石子有次序地合并成一堆。规定在合并过程中最多可以有 m(k)次选 k 堆石子合并成新的一堆,2≤k≤n,合并的费用为新的一堆的石子数。试设计一个算法,计算出将 n 堆石子合并成一堆的最小总费用。
对于给定 n 堆石子,编程计算合并成一堆的最小总费用。
数据输入:
第 1 行有 1 个正整数 n,表示有 n 堆石子。第 2行有 n 个数,分别表示每堆石子的个数。第 3 行有 n-1 个数,分别表示 m(k)(2≤k≤n)的值。
Java
import java.util.PriorityQueue;
import java.util.Scanner;
public class DuoYuanHuffmanBianMaBianXing {
private static int n;
private static int[] b,c;
private static boolean found;
private static PriorityQueue<Integer> a;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while (true){
n = input.nextInt();
a = new PriorityQueue<>(n+1);
b = new int[n+1];
c = new int[n+1];
for(int i=1; i<=n; i++)
a.add(input.nextInt());
for(int i=2; i<=n; i++)
c[i] = input.nextInt();
for(int i=0; i<=n; i++)
b[i] = 0;
found = false;
search(0,0);
int result=0;
if(!found)
System.out.println("No Solution!");
else
result = guffman(a,b);
System.out.println(result);
}
}
private static void search(int dep, int sum){
if(dep == n-1){
if(sum == n-1)
found = true;
return;
}
int ii = n/(n-dep-1);
if(ii > c[n-dep])
ii = c[n-dep];
for(int i=ii; i>=0; i--){
b[n-dep] = i;
sum += i*(n-dep-1);
search(dep+1,sum);
if(found) return;
sum -= i*(n-dep-1);
}
}
private static int guffman(PriorityQueue<Integer> a, int[] b){
int i,j,k,t,sum=0;
for(i=2; i<=n; i++){
for(k=1; k<=b[i]; k++){
for(j=1,t=0; j<=i; j++)
t += a.poll();
sum += t;
a.add(t);
}
}
return sum;
}
}
Input & Output
7
45 13 12 16 9 5 22
3 3 0 2 1 0
136
Reference
王晓东《计算机算法设计与分析》