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
| #include <bits/stdc++.h>
using namespace std;
struct node {
int cnt;
node *left, *right;
node() = default;
} *rt = nullptr;
void trie_insert(node *&p, const basic_string<char> &s, const int depth) {
if (!p) {
p = new node();
}
if (depth == s.size()) {
p->cnt++;
} else {
if (s[depth] == '0') {
trie_insert(p->left, s, depth + 1);
} else {
trie_insert(p->right, s, depth + 1);
}
}
}
using set_t = priority_queue<int, vector<int>, greater<>>;
int64_t ans = 0;
void ins(set_t &f, set_t &e, int c, const int depth) {
while (c) {
if (f.empty()) {
ans += e.top() - depth;
f.push(e.top());
e.pop();
} else if (e.empty()) {
const int x = f.top();
f.pop();
ans += x - depth + 2;
f.push(x + 1);
f.push(x + 1);
} else {
if (e.top() < f.top() + 2) {
ans += e.top() - depth;
f.push(e.top());
e.pop();
} else {
const int x = f.top();
f.pop();
ans += x - depth + 2;
f.push(x + 1);
f.push(x + 1);
}
}
c--;
}
}
pair<set_t *, set_t *> query(const node *const p, const int depth) {
// 前满后空
if (!p) {
auto *q = new set_t();
q->push(depth);
return {new set_t(), q};
} else {
if (!p->left && !p->right) {
auto *q = new set_t(), *tmp = new set_t();
q->push(depth);
ins(*q, *tmp, p->cnt - 1, depth);
return {q, tmp};
} else {
auto [x,y] = query(p->left, depth + 1);
auto [u,v] = query(p->right, depth + 1);
if (x->size() < u->size()) {
swap(x, u);
}
while (!u->empty()) {
x->push(u->top());
u->pop();
}
if (y->size() < v->size()) {
swap(y, v);
}
while (!v->empty()) {
y->push(v->top());
v->pop();
}
ins(*x, *y, p->cnt, depth);
return {x, y};
}
}
}
int n;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for (int i = 0; i < n; ++i) {
basic_string<char> s;
cin >> s;
trie_insert(rt, s, 0);
}
query(rt, 0);
cout << ans;
return 0;
}
|