AT1219 歴史の研究

题目描述

https://www.luogu.com.cn/problem/AT1219

Solution

区间加权众数,这东西不太支持删除,所以我们用回滚莫队即可

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
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#define maxn 100010
#define ll long long
using namespace std;

int n, m, k, a[maxn];

int b[maxn];
void init_hash() {
for (int i = 1; i <= n; ++i) b[i] = a[i];
sort(b + 1, b + n + 1); int cnt = unique(b + 1, b + n + 1) - b - 1;
for (int i = 1; i <= n; ++i) a[i] = lower_bound(b + 1, b + cnt + 1, a[i]) - b;
}

int blo, bl[maxn], R[maxn];
struct Query {
int l, r, k, id;

friend bool operator < (const Query &u, const Query &v) {
if (bl[u.l] == bl[v.l]) return u.r < v.r;
return u.l < v.l;
}
} Q[maxn];

ll s1[maxn], s2[maxn], Ans[maxn], ans;
inline void add(int v, ll &ans) {
s1[v] += b[v];
ans = max(ans, s1[v]);
}

inline void Add(int v, ll &ans) {
s2[v] += b[v];
ans = max(ans, s1[v] + s2[v]);
}


int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n >> m; blo = sqrt(n);
for (int i = 1; i <= n; ++i) cin >> a[i]; init_hash();
for (int i = 1; i <= m; ++i) cin >> Q[i].l >> Q[i].r, Q[i].id = i;
for (int i = 1; i <= n; ++i) bl[i] = (i - 1) / blo + 1, R[bl[i]] = bl[i] * blo;
sort(Q + 1, Q + m + 1);
for (int o = 1, p = 1; o <= m; o = p) {
while (bl[Q[o].l] == bl[Q[p].l]) ++p;
ll ans = 0; int r = R[bl[Q[o].l]], _r = r; fill(s1, s1 + maxn, 0);
for (int i = o; i < p; ++i) {
while (r < Q[i].r) add(a[++r], ans);
Ans[Q[i].id] = ans;
for (int j = Q[i].l; j <= min(Q[i].r, _r); ++j) Add(a[j], Ans[Q[i].id]);
for (int j = Q[i].l; j <= min(Q[i].r, _r); ++j) s2[a[j]] = 0;
}
}
for (int i = 1; i <= m; ++i) cout << Ans[i] << "\n";
return 0;
}