1、解题思路:哈夫曼树。
2、注意事项:STL中优先队列容器(priority_queue)的应用,定义__int64位ans。
3、实现方法:
1
#include
<
iostream
>
2 #include < queue >
3 using namespace std;
4
5 struct Node
6 {
7 __int64 x;
8 bool operator < ( const Node & a) const
9 {
10 return a.x < x;
11 }
12 };
13
14 int main()
15 {
16 int n;
17 __int64 ans,N1,N2;
18 Node tmp;
19 priority_queue < Node > Q;
20 cin >> n;
21 for ( int i = 0 ;i < n;i ++ )
22 {
23 scanf( " %I64d " , & tmp.x);
24 Q.push(tmp);
25 }
26 ans = 0 ;
27 while ( ! Q.empty() && Q.size() >= 2 )
28 {
29 N1 = Q.top().x;
30 Q.pop();
31 N2 = Q.top().x;
32 Q.pop();
33 ans += N1 + N2;
34 tmp.x = N1 + N2;
35 Q.push(tmp);
36 }
37 printf( " %I64d\n " ,ans);
38 return 0 ;
39 }
2 #include < queue >
3 using namespace std;
4
5 struct Node
6 {
7 __int64 x;
8 bool operator < ( const Node & a) const
9 {
10 return a.x < x;
11 }
12 };
13
14 int main()
15 {
16 int n;
17 __int64 ans,N1,N2;
18 Node tmp;
19 priority_queue < Node > Q;
20 cin >> n;
21 for ( int i = 0 ;i < n;i ++ )
22 {
23 scanf( " %I64d " , & tmp.x);
24 Q.push(tmp);
25 }
26 ans = 0 ;
27 while ( ! Q.empty() && Q.size() >= 2 )
28 {
29 N1 = Q.top().x;
30 Q.pop();
31 N2 = Q.top().x;
32 Q.pop();
33 ans += N1 + N2;
34 tmp.x = N1 + N2;
35 Q.push(tmp);
36 }
37 printf( " %I64d\n " ,ans);
38 return 0 ;
39 }