霍夫曼编码,这个是把霍夫曼树也建好了的!必须把输入改为char才能ac,好坑......
http://soj.sysu.edu.cn/show_problem.php?pid=1002&cid=1740
1 #include <iostream> 2 #include <cstring> 3 #include <queue> 4 #include <algorithm> 5 #include <vector> 6 #include <cstdio> 7 8 using namespace std; 9 10 struct HuffmanNode { 11 char ch; 12 int frequency; 13 HuffmanNode *lc, *rc; 14 HuffmanNode():ch(0), frequency(0), lc(NULL), rc(NULL){} 15 }; 16 17 struct cmp { 18 bool operator()(HuffmanNode* a, HuffmanNode* b) 19 { 20 return a->frequency > b->frequency; 21 } 22 }; 23 24 vector<int> v; 25 void code(HuffmanNode* r) 26 { 27 if(r->lc==NULL && r->rc==NULL) 28 { 29 cout << r->ch <<": "; //打印字符的编码 30 for (int i = 0; i<v.size(); i++) 31 cout << v[i]; 32 cout << endl; 33 v.pop_back(); //注意pop 34 return ; 35 } 36 if(r->lc) 37 { 38 v.push_back(0); 39 code(r->lc); 40 } 41 if(r->rc) 42 { 43 v.push_back(1); 44 code(r->rc); 45 } 46 if(!v.empty()) 47 v.pop_back(); //注意pop 48 } 49 50 int main() 51 { 52 int n; 53 cin >> n; 54 char ch;// c; 55 int f; 56 57 priority_queue<HuffmanNode*, vector<HuffmanNode*>, cmp>q; 58 59 for(int i=0; i<n; i++) 60 { 61 HuffmanNode* h = new HuffmanNode; 62 cin >> ch >> f; 63 //scanf("%c %d", &ch, &f); 64 h->ch = ch; 65 h->frequency = f; 66 q.push(h); 67 } 68 69 int res=0; 70 while(q.size() > 1) 71 { 72 HuffmanNode* temp1 = new HuffmanNode; 73 temp1 = q.top(); 74 q.pop(); 75 HuffmanNode* temp2 = new HuffmanNode; 76 temp2 = q.top(); 77 q.pop(); 78 79 HuffmanNode* temp = new HuffmanNode; 80 temp->frequency = temp1->frequency + temp2->frequency; 81 temp->lc = temp1; 82 temp->rc = temp2; 83 84 res += temp1->frequency + temp2->frequency; 85 q.push(temp); 86 } 87 cout << res << endl; 88 HuffmanNode* root = q.top(); 89 //code(root); 90 91 return 0; 92 }