标签:
题意:给你一个序列 ,让你求这个序列组成哈夫曼树的 WPL
解题思路:优先队列直接搞。因为数太大,用了非递归求解。
解题代码:
1 #pragma comment(linker, "/STACK:1024000000,1024000000") 2 // File Name: c.cpp 3 // Author: darkdream 4 // Created Time: 2015年04月14日 星期二 18时35分42秒 5 6 #include<vector> 7 #include<list> 8 #include<map> 9 #include<set> 10 #include<deque> 11 #include<stack> 12 #include<bitset> 13 #include<algorithm> 14 #include<functional> 15 #include<numeric> 16 #include<utility> 17 #include<sstream> 18 #include<iostream> 19 #include<iomanip> 20 #include<cstdio> 21 #include<cmath> 22 #include<cstdlib> 23 #include<cstring> 24 #include<ctime> 25 #include<queue> 26 #define LL long long 27 #define maxn 500005 28 using namespace std; 29 struct node{ 30 LL v; 31 int num ; 32 node(){} 33 node(LL _v , int _num){ 34 v = _v ; 35 num = _num; 36 } 37 bool operator < (const node &b )const { 38 return v > b.v; 39 } 40 }; 41 priority_queue<node> qu ; 42 43 int n ; 44 int ch[maxn*4][2]; 45 int que[maxn*4]; 46 int deep[maxn*4]; 47 LL a[maxn]; 48 int tot; 49 int main(){ 50 freopen("huffman.in","r",stdin); 51 freopen("huffman.out","w",stdout); 52 scanf("%d",&n); 53 for(int i = 1;i <= n;i ++){ 54 scanf("%I64d",&a[i]); 55 qu.push(node(a[i],i)); 56 } 57 tot = n; 58 while(qu.size()!= 1){ 59 node ta,tb; 60 ta = qu.top(); 61 qu.pop(); 62 tb = qu.top(); 63 qu.pop(); 64 //printf("%I64d %d %I64d %d\n",ta.v,ta.num,tb.v,tb.num); 65 tot ++ ; 66 ch[tot][0] = ta.num; 67 ch[tot][1] = tb.num; 68 qu.push(node(ta.v+tb.v,tot)); 69 } 70 LL ans = 0 ; 71 int head = 0 ; 72 int tail = 0 ; 73 deep[tot] = 0 ; 74 for(que[tail++] = tot ; head < tail ;head ++) 75 { 76 //printf("%d %d %d\n",que[head],ch[que[head]][0],ch[que[head]][1]); 77 //:printf("%d\n",deep[que[head]]); 78 if(ch[que[head]][0]){ 79 que[tail] = ch[que[head]][0]; 80 deep[ch[que[head]][0]] = deep[que[head]] + 1; 81 tail ++ ; 82 } 83 if(ch[que[head]][1]){ 84 que[tail] = ch[que[head]][1]; 85 deep[ch[que[head]][1]] = deep[que[head]] + 1; 86 tail ++ ; 87 } 88 } 89 for(int i = 1;i <= n;i ++) 90 ans += 1ll * deep[i] * a[i]; 91 printf("%I64d\n",ans); 92 return 0; 93 }
标签:
原文地址:http://www.cnblogs.com/zyue/p/4427318.html