题解:SP1684 FREQUENT - Frequent values
\textbf{Description}
给定一个长度为
机器翻译:一个天真的算法可能无法及时运行!
那么一个不天真的算法呢?大雾
\textbf{Solution}
我爱优雅的暴力!
多测不清空,爆零两行泪!
多测不清空,爆零两行泪!
多测不清空,爆零两行泪!
#include <bits/stdc++.h>
const int N = 2e5 + 10;
int n, q, siz, tot, now, tmp, a[N], L[N], R[N], id[N], cnt[N], _cnt[N], ans[N];
struct Query {
int l, r, pos;
bool operator<(const Query &x) const {
return (id[l] ^ id[x.l]) ? id[l] < id[x.l] : r < x.r;
}
} b[N];
void init() {
std::cin >> q;
siz = 0, tot = 0, now = 0, tmp = 0;
siz = sqrt(n), now = 0;
for (int i = 1; i <= n; ++i)
std::cin >> a[i], a[i] += 1e5;
for (int i = 1; i <= q; ++i)
std::cin >> b[i].l >> b[i].r, b[i].pos = i, ans[i] = 0;
// 分块
tot = n / siz;
for (int i = 1; i <= tot; ++i) {
L[i] = siz * (i - 1) + 1;
R[i] = siz * i;
}
if (R[tot] < n) {
++tot;
L[tot] = R[tot - 1] + 1;
R[tot] = n;
}
for (int i = 1; i <= tot; ++i)
for (int j = L[i]; j <= R[i]; ++j)
id[j] = i;
memset(cnt, 0, sizeof(cnt));
std::sort(b + 1, b + q + 1);
}
void add(int x, int &u) {
++cnt[x];
u = std::max(u, cnt[x]);
}
void del(int x) {
--cnt[x];
}
int main() {
std::cin.tie(0)->sync_with_stdio(0);
while (std::cin >> n && n) {
init();
for (int i = 1, l = 1, r = 0, lst = 0, _l; i <= q; ++i) {
int ql = b[i].l, qr = b[i].r;
if (id[ql] == id[qr]) { // 如果询问区间在一个块内,直接暴力计算
for (int u = ql; u <= qr; ++u) ++_cnt[a[u]];
for (int u = ql; u <= qr; ++u)
ans[b[i].pos] = std::max(ans[b[i].pos], _cnt[a[u]]); // 这里就是清空 ans 的数组的原因
for (int u = ql; u <= qr; ++u) --_cnt[a[u]];
continue;
}
if (id[ql] != lst) { // 左端点进入了一个新的块,重置
while (r > R[id[ql]]) del(a[r--]);
while (l < R[id[ql]] + 1) del(a[l++]);
lst = id[ql], now = 0;
}
while (r < qr) add(a[++r], now); // 扩展右端点
tmp = now, _l = l;
while (_l > ql) add(a[--_l], tmp); // 扩展左端点的副本
ans[b[i].pos] = tmp; // 记录答案
while (_l < l) del(a[_l++]); // 回滚
}
for (int i = 1; i <= q; ++i)
std::cout << ans[i] << "\n";
}
std::cout.flush();
return 0;
}