poj 3253 最小堆 优先队列 哈夫曼树
来源:互联网 发布:js中name选择器 编辑:程序博客网 时间:2024/05/22 01:37
import java.io.*;class Heap {private final int maxn = 50010;int[] data;int r;Heap() {data = new int[maxn];r = 0;}public int size() {return r;}void swap(int a, int b) {int tmp = data[a];data[a] = data[b];data[b] = tmp;}void up(int p) {if (!(p > 0))return;int q = p >> 1;if (data[p] < data[q]) {swap(p, q);up(q);}}void down(int p) {int q;if ((p << 1) >= r)return;else if ((p << 1) == r - 1) {q = p << 1;} else {q = (data[p << 1] < data[p << 1 | 1] ? p << 1 : p << 1 | 1);}if (data[p] > data[q]) {swap(p, q);down(q);}}void push(int n) {data[r++] = n;up(r - 1);}int pop() {int res = data[0];swap(0, r - 1);r--;down(0);return res;}int top() {return data[0];}}public class Main {private static long solve(int[] a) {Heap hp = new Heap();int n = a[0], l1, l2;long res = 0;for (int i = 1; i <= n; i++)hp.push(a[i]);// hp.print();while (hp.size() > 1) {l1 = hp.pop();l2 = hp.pop();res += (long) (l1 + l2);hp.push(l1 + l2);}return res;}public static void main(String[] args) throws IOException {StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));PrintWriter out = new PrintWriter(System.out);while (in.nextToken() != StreamTokenizer.TT_EOF) {int n = (int) in.nval;int[] a = new int[n + 1];a[0] = n;for (int i = 1; i <= n; i++) {in.nextToken();a[i] = (int) in.nval;}if (n > 1)out.println(solve(a));elseout.println(a[1]);out.flush();}out.close();}}
0 0
- poj 3253 最小堆 优先队列 哈夫曼树
- POJ 2051(最小堆/优先队列)
- poj 3253 优先队列 堆
- Poj 2051 Argus (最小堆/优先队列)
- 最小优先队列--堆实现
- 优先队列(最小堆)
- 最小堆模拟优先队列
- 优先队列及最小堆最大堆
- 优先队列及最大堆最小堆
- 堆排序和优先队列【最小堆】
- 优先队列及最小堆最大堆
- 优先队列及最小堆最大堆
- 优先队列及最小堆最大堆
- 优先队列&&最小堆&&最大堆
- 最小堆及基于最小堆的最小优先队列
- 优先队列模拟最大堆和最小堆,poj 1442 Black Box
- poj 3253 【哈夫曼树】【优先队列】
- 最小堆优先队列C++实现
- 通过Eclipse的Install New Software方式安装jbpm6
- Wormholes
- poj 2481 比壮的牛 树状数组
- Maven的安装和配置
- 解决ANDROID中文乱码问题
- poj 3253 最小堆 优先队列 哈夫曼树
- 最惊讶的算法
- Scala : 单例对象、伴生类、伴生对象
- 静态代码块
- 七月十四日 Linux操作系统c语言学习笔记
- android开发步步为营之66:android图片选取
- 【iOS开发系列】NSSet & NSIndexSet
- RatingBar 在activity中代码控制监听
- UI基础(一)