-
Notifications
You must be signed in to change notification settings - Fork 1
/
#1315_字符串编码
107 lines (90 loc) · 2.33 KB
/
#1315_字符串编码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//
// Created by mingy on 2016-04-02.
//
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
string s;
vector<char> new_s;
string table[256];
struct Node {
int weight;
char ch;
Node *left;
Node *right;
Node():left(NULL), right(NULL), ch('0'), weight(0){}
};
struct cmp_each_char{
bool operator()(Node *a, Node *b){
return a->weight > b->weight;
}
};
priority_queue <Node*, vector<Node*>, cmp_each_char> pq_Nodes;
bool isNewCh(char ch) {
for (int i = 0; i < new_s.size(); ++i)
if (ch == new_s[i])
return false;
return true;
}
void show(Node* x){
if(x->left == NULL && x->right == NULL){
cout <<x->ch << "\t" <<x->weight<< endl;
return;
}
show(x->left);
show(x->right);
}
void buildTable(Node* x, string st){
if(x->left == NULL && x->right == NULL){
table[x->ch] = st;
return;
}
buildTable(x->left, st + "1");
buildTable(x->right, st + "0");
}
int main() {
cin >> s;
for (int i = 0; i < s.length(); ++i)
if (isNewCh(s[i]))
new_s.push_back(s[i]);
vector <Node> each_char;
for (int i = 0; i < new_s.size(); ++i) {
Node * new_char = new Node();
new_char->ch = new_s[i];
each_char.push_back(*new_char);
}
for (int i = 0; i < new_s.size(); ++i)
for (int j = 0; j < s.size(); ++j)
if (s[j] == new_s[i])
each_char[i].weight++;
for (int i = 0; i < new_s.size(); ++i)
pq_Nodes.push(&each_char[i]);
while(pq_Nodes.size() > 1){
Node * a= pq_Nodes.top();
pq_Nodes.pop();
Node * b = pq_Nodes.top();
pq_Nodes.pop();
Node * parent = new Node();
parent->weight = b->weight + a->weight;
parent->left = b;
parent->right = a;
pq_Nodes.push(parent);
}
buildTable(pq_Nodes.top(), "");
int count = 0;
for (int i = 0; i < s.size(); ++i)
count += table[s[i]].size();
if (new_s.size() == 1)
count = s.size();
cout << count << endl;
return 0;
}
/**************************************************************
Problem: 1315
User: 22920142203903
Language: C++
Result: Accepted
Time:74 ms
Memory:1772 kb
****************************************************************/