3253

1 /*
2 好题,把哈夫曼编码的思想融汇进来
3 初看好像是贪心,结果是错的。后来举个例子,发现,贪心果然不行。
4
5 可把所有的木板的长度看成是一课二叉树的叶子节点。为什么要二叉树呢?因为根据题意,每个木板切开之后会形成左右两个木板
6 可以模型化为二叉树。最后的问题可以归结为:所有叶子节点的权乘以路径长度的和,也就是说带权路径长度的和的最小值了
7 这其实就是求最优二叉树(哈弗曼树)
8
9 带权路径长度综合
10 weighted path length of tree
11 哈夫曼编码
12 */
13
14 // include file
15 #include <cstdio>
16 #include <cstdlib>
17 #include <cstring>
18 #include <cmath>
19 #include <cctype>
20 #include <ctime>
21
22 #include <iostream>
23 #include <sstream>
24 #include <fstream>
25 #include <iomanip>
26 #include <bitset>
27 #include <strstream>
28
29 #include <algorithm>
30 #include <string>
31 #include <vector>
32 #include <queue>
33 #include <set>
34 #include <list>
35 #include <functional>
36
37 using namespace std;
38
39 // typedef
40 typedef long long LL;
41 typedef unsigned long long ULL;
42 typedef __int64 Bint;
43
44 //
45 #define read freopen("in.txt","r",stdin)
46 #define write freopen("out.txt","w",stdout)
47 #define FORi(a,b,c) for(int i=(a);i<(b);i+=c)
48 #define FORj(a,b,c) for(int j=(a);j<(b);j+=c)
49 #define FORk(a,b,c) for(int k=(a);k<(b);k+=c)
50 #define FORp(a,b,c) for(int p=(a);p<(b);p+=c)
51 #define FORii(a,b,c) for(int ii=(a);ii<(b);ii+=c)
52 #define FORjj(a,b,c) for(int jj=(a);jj<(b);jj+=c)
53 #define FORkk(a,b,c) for(int kk=(a);kk<(b);kk+=c)
54
55 #define FF(i,a) for(int i=0;i<(a);i+++)
56 #define FFD(i,a) for(int i=(a)-1;i>=0;i--)
57 #define Z(a) (a<<1)
58 #define Y(a) (a>>1)
59
60 const double eps = 1e-6;
61 const double INFf = 1e10;
62 const int INFi = 1000000000;
63 const double Pi = acos(-1.0);
64
65 template<class T> inline T sqr(T a){return a*a;}
66 template<class T> inline T TMAX(T x,T y)
67 {
68 if(x>y) return x;
69 return y;
70 }
71 template<class T> inline T TMIN(T x,T y)
72 {
73 if(x<y) return x;
74 return y;
75 }
76 template<class T> inline void SWAP(T &x,T &y)
77 {
78 T t = x;
79 x = y;
80 y = t;
81 }
82 template<class T> inline T MMAX(T x,T y,T z)
83 {
84 return TMAX(TMAX(x,y),z);
85 }
86
87
88 // code begin
89 #define MAXN 20010
90 int N;
91 struct node
92 {
93 node()
94 {
95 v=0;
96 }
97 node(Bint vv)
98 {
99 v=vv;
100 }
101 Bint v;
102 friend bool operator<(node a,node b)
103 {
104 return a.v>b.v;
105 }
106 };
107 priority_queue<node> pq;
108 Bint ans,sum,in;
109 node a,b;
110 int main()
111 {
112 read;
113 write;
114 while(scanf("%d",&N)!=-1)
115 {
116 while(!pq.empty())
117 pq.pop();
118 FORi(0,N,1)
119 {
120 scanf("%I64d",&in);
121 pq.push(node(in));
122 }
123 if(N==1)
124 {
125 printf("0\n");
126 continue;
127 }
128
129 ans = 0;
130 while(pq.size()>1)
131 {
132 a = pq.top();
133 pq.pop();
134 b = pq.top();
135 pq.pop();
136 sum = a.v+b.v;
137 ans += sum;
138 pq.push(node(sum));
139 }
140 printf("%I64d\n",ans);
141 }
142 return 0;
143 }
posted @ 2011-03-09 10:23  AC2012  阅读(331)  评论(0编辑  收藏  举报