-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzip.cpp
More file actions
132 lines (108 loc) · 2.52 KB
/
zip.cpp
File metadata and controls
132 lines (108 loc) · 2.52 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <bits/stdc++.h>
#define ln '\n'
#define loop(i,a,b) for(int i = a; i <= b; i++)
#define pb push_back
using namespace std;
ifstream fin("file.txt", ios::binary);
ofstream fout("file.myzip", ios::binary);
uint8_t curr = 0;
int bitCount = 0;
char c;
unordered_map<char, string> ans;
class Node{
public:
char val;
int data;
Node *left, *right;
Node(char x, int y){
val = x;
data = y;
left = nullptr;
right = nullptr;
}
};
class Compare{
public:
bool operator() (Node* a, Node* b){
return a->data > b->data;
}
};
void preorder(Node* root, string curr){
if(root == nullptr)return;
if(root->left == nullptr && root->right == nullptr){
ans[root->val] = curr;
return;
}
preorder(root->left, curr + '0');
preorder(root->right, curr + '1');
}
void huffmanCoding(vector<pair<char, int>> freq){
int n = freq.size();
priority_queue<Node*, vector<Node*>, Compare>pq;
for(int i = 0; i < n; i++){
Node *tmp = new Node(freq[i].first, freq[i].second);
pq.push(tmp);
}
while(pq.size() >= 2){
Node *l = pq.top();
pq.pop();
Node *r = pq.top();
pq.pop();
Node *x = new Node('x', l->data + r->data);
x->left = l;
x->right = r;
pq.push(x);
}
preorder(pq.top(), "");
}
unordered_map<char, int> mp;
vector<pair<char, int>> freq;
int main(){
auto writeBit = [&](int bit){
curr = (curr << 1) | bit;
bitCount++;
if(bitCount == 8){
fout.put(curr);
curr = 0;
bitCount = 0;
}
};
while(fin.get(c)){
mp[c]++;
}
fin.clear();
fin.seekg(0, ios::beg);
uint8_t nr = mp.size();
for(int i = 7; i >= 0; i--){
writeBit((nr >> i) & 1);
}
for(auto i : mp){
freq.pb({i.first, i.second});
}
huffmanCoding(freq);
uint8_t x;
for(auto i : mp){
x = i.first;
for(int j = 7; j >= 0; j--){
writeBit((x >> j) & 1);
}
x = ans[i.first].size();
for(int j = 7; j >= 0; j--){
writeBit((x >> j) & 1);
}
for(auto b : ans[i.first])writeBit(b - '0');
int nr = (8 - x % 8) % 8;
for(int j = 0; j < nr; j++)writeBit(0);
}
while(fin.get(c)){
string code = ans[c];
for(char b : code){
writeBit(b - '0');
}
}
if(bitCount > 0){
curr <<= (8 - bitCount);
fout.put(curr);
}
return 0;
}