解題思路
複製陣列一次。詢問i≤j用[i−1,j−1],否則用[i−1,j−1+n],每個圓形區間都成為不超過n長的線性區間。
以Mo順序排序詢問,維護每個項目的次數cnt、每個正次數有幾種項目的bucket,以及當前最大次數mx。移動左右端點時,先從舊bucket移出、更新cnt、再加入新bucket,移除時必要則縮小mx。
bucket[mx]=1時輸出mx,否則輸出bucket[mx]。頻率與其種類數分開維護,故可O(1)回答每筆;離線排序只改處理順序,答案依原索引保存。
時間O((n+Q)√n),空間O(n+Q+最大項目編號);Python read().split()另有O(n+Q)輸入暫存。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。
Step-by-step animation
教學示意(以步驟描述中的輸入為準)
步驟 1 / 3
示意區間1,2,1
次數為1:2、2:1。
1
2
1
- mx
- 2
- bucket[2]
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, Q;
cin >> n >> Q;
vector<int> a(2 * n);
for (int i = 0; i < n; i++) {
cin >> a[i];
a[i + n] = a[i];
}
int B = max(1, (int)sqrt(2 * n));
vector<array<int, 3>> q(Q);
for (int z = 0; z < Q; z++) {
int l, r;
cin >> l >> r;
--l;
--r;
if (r < l)
r += n;
q[z] = {l, r, z};
}
sort(q.begin(), q.end(), [&](auto a, auto b) {
if (a[0] / B != b[0] / B)
return a[0] / B < b[0] / B;
return (a[0] / B) % 2 ? a[1] > b[1] : a[1] < b[1];
});
vector<int> cnt(100001), bucket(n + 1), ans(Q);
int L = 0, R = -1, mx = 0;
auto change = [&](int x, int delta) {
int old = cnt[x];
if (old)
bucket[old]--;
cnt[x] += delta;
if (cnt[x])
bucket[cnt[x]]++;
mx = max(mx, cnt[x]);
while (mx && !bucket[mx])
mx--;
};
for (auto [l, r, id] : q) {
while (L > l)
change(a[--L], 1);
while (R < r)
change(a[++R], 1);
while (L < l)
change(a[L++], -1);
while (R > r)
change(a[R--], -1);
ans[id] = bucket[mx] == 1 ? mx : bucket[mx];
}
for (int x : ans)
cout << x << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。