切金条_哈夫曼编码

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

/**
 * 一块金条切成两半,是需要花费和长度数值一样的铜板的。
 * 比如长度为20的 金条,不管切成长度多大的两半,都要花费20个铜板。
 * 一群人想整分整块金 条,怎么分最省铜板?
 * 
 * 例如,给定数组{10,20,30},代表一共三个人,
 * 整块金条长度为10+20+30=60. 金条要分成10,20,30三个部分。 
 * 如果,先把长度60的金条分成10和50,花费60 再把长度50的金条分成20和30,花费50,一共花费110铜板。
 * 但是如果, 先把长度60的金条分成30和30,花费60 再把长度30金条分成10和20,花费30,一共花费90铜板。
 * 
 * 输入一个数组返回分割的最小值。
 * @author 小纸人
 *
 */
public class CutGold {

	//List 集合做法
//	static class MyComparator implements Comparator<Integer>{
//		public int compare(Integer o1, Integer o2) {
//			return o1 - o2;
//		}
//	}
//	public static int cut(int[] arr) {
//		int cost  = 0;
//		List<Integer> goldList = new ArrayList<Integer>();
//		for (int i = 0; i < arr.length; i++) {
//			goldList.add(arr[i]);
//		}
//		goldList.sort(new MyComparator());
//		while(goldList.size() > 1) {
//			cost += (goldList.get(0) + goldList.get(1));
//			goldList.add(goldList.get(0) + goldList.get(1));
//			goldList.remove(0);
//			goldList.remove(0);
//			goldList.sort(new MyComparator());
//		}
//		return cost;
//	}
	
	//优先队列做法
	public static int cut(int[] arr) {
		int res = 0;
		PriorityQueue<Integer> queue = new PriorityQueue<>();
		for (int i = 0; i < arr.length; i++) {
			queue.add(arr[i]);
		}
		while(queue.size() > 1) {
			int temp = queue.poll() + queue.poll(); 
			res += temp;
			queue.add(temp);
		}
		return res;
	}
	public static void main(String[] args) {
		int[] gold = {10, 20, 30};
		System.out.println(cut(gold));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值