版本比较
(*3100,莫队,根号分治)CF700D Huffman Coding on Segment 题解
正文
增加 12 行删除 28 行
2 行未改动34567789101124 行未改动36373839404042434445464748494142434420 行未改动65666768787980697082717284857374757677787980819582838485865 行未改动9293949510996979899100101102103117118119120121104105123124125126106107108109110111112128113114115116228 行未改动全部展开2 行未改动哈夫曼编码的计算方式是每次从堆里取出出现次数最少的两个合并,合并时的代价为两个出现次数之和。
## 基于莫队的暴力做法
由于是区间问题,考虑莫队,维护实时每个数出现次数 $c_i$ 和每种次数有多少个不同的数 $d_i$。计算答案时,按照哈夫曼编码计算方式暴力计算,此时时间复杂度为 $\mathcal O(q n \sqrt{n})$,不可过。由于是区间问题,考虑莫队,维护实时每个数出现次数 $c_i$ 和每种次数有多少个不同的数 $d_i$。计算答案时,按照哈夫曼编码计算方式暴力计算,此时时间复杂度为 $\mathcal O(q n \log{n})$,不可过。
## 根号分治
根据每个数出现次数的性质,我们可以对它们按照 $B=\sqrt{n}$ 进行根号分治:24 行未改动
int n, q, a[N], L = 1, R = 0;int c[N], d[N], cur[N], ans[N];vector<int> cd;queue<int> q1, q2;
int getmin() { if (q1.empty() && q2.empty()) { return -1; } if (q2.empty()) { int r = q1.front(); q1.pop(); return r; } if (q1.empty()) { int r = q2.front(); q2.pop(); return r; } if (q1.front() < q2.front()) { int r = q1.front(); q1.pop(); return r; } if (q1.front() >= q2.front()) { int r = q2.front(); q2.pop(); return r; }}
inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') {20 行未改动void ins(int x) { d[c[x]]--, c[x]++, d[c[x]]++; }void del(int x) { d[c[x]]--, c[x]--, d[c[x]]++; }
int calc() { while (!q1.empty()) { q1.pop(); } while (!q2.empty()) { q2.pop(); } vector<int> vec; priority_queue<int, vector<int>, greater<int> > q; for (int i : cd) { if (c[i] > B) { vec.push_back(c[i]); } if (c[i] > B) { q.push(c[i]); } } sort(vec.begin(), vec.end()); for (int i : vec) { q1.push(i); } int ret = -1, res = 0; for (int i = 0; i <= B; i++) { cur[i] = d[i]; } for (int i = 1; i <= B; i++) { if (cur[i] == 0) { continue; } if (ret != -1) { cur[i]--; int nw = i + ret; res += nw; if (nw > B) { q2.push(nw); q.push(nw); } else { cur[nw]++; } ret = -1;5 行未改动 int nw = i + i; res += nw * (cur[i] / 2); if (nw > B) { for (int j = 1; j <= cur[i] / 2; j++) { q2.push(nw); q.push(nw); } } else { cur[nw] += cur[i] / 2; } cur[i] = 0; } if (ret != -1) { q1.push(ret); vec.clear(); while (!q1.empty()) { vec.push_back(q1.front()), q1.pop(); } sort(vec.begin(), vec.end()); for (int i : vec) { q1.push(i); } q.push(ret); } while (1) { int num1 = getmin(), num2 = getmin(); if (num1 == -1 || num2 == -1) { break; } int num = num1 + num2; while ((int)q.size() >= 2) { int num = q.top(); q.pop(); num += q.top(); q.pop(); q.push(num); res += num; q2.push(num); } return res;}
228 行未改动全部展开