概述
题意:求区间数字出现次数的mex,带修改
莫队算法小结
问题:n个数,q次询问[l, r]内不重复数字个数。
思路:由于区间数字种数不具有区间加和性质,故无法直接用线段数来处理。
莫队算法是一种分块的思想,在已知[l,r]结果情况下,可以在O(1)的时间求出临近区间的解。
如果将每个区间抽象成平面上的点,离线出所有区间结果的花费等价于求曼哈顿最小生成树。
把区间分块,每块为root(q),算法的时间复杂度为O(n^1.5)。
实现过程:
用pos数组维护每个点所在的块,以l所在的块为主关键字,r的为次关键字排序。
定义初始l=1,r=0,按此顺序进行离线,不断调整l与r的位置,同时维护cnt。
带修莫队
支持单点修改,引入修改时间,表示当前的询问是发生在第T次修改之后的。
类似l,r,只需要将t指针移动即可。排序时将t作为第三关键字。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200005;
typedef long long ll;
int n, m;
int a[maxn];
int be[maxn], num[maxn], now[maxn], cnt[maxn], ans[maxn];
map<int, int> M;
int msz;
struct Query {
int l, r, t, id;
bool operator<(const Query &rhs) const {
return be[l] == be[rhs.l] ?
(be[r] == be[rhs.r] ? t < rhs.t : r < rhs.r) : l < rhs.l;
}
}q[maxn];
int qsz;
struct Change {
int pos, New, Old;
}c[maxn];
int csz;
int T = 0, l = 1, r = 0;
int compress(int x) {
if(!M.count(x)) M[x] = ++msz;
return M[x];
}
void add(int val, int d) {
if(num[val] > 0) cnt[num[val]]--;
num[val] += d;
if(num[val] > 0) cnt[num[val]]++;
}
void go(int idx, int val) {
if(l <= idx && idx <= r) {
add(a[idx], -1);
add(val, 1);
}
a[idx] = val;
}
int get() {
for(int i = 1; ;++i) {
if(cnt[i] == 0) return i;
}
}
int main() {
cin >> n >> m;
int unit = pow(n, 0.6666);
for(int i = 1, x; i <= n; ++i) {
scanf("%d", &x);
be[i] = (i-1)/unit + 1;
now[i] = a[i] = compress(x);
}
for(int i = 1; i <= m; ++i) {
int op, x, y;
scanf("%d%d%d", &op, &x, &y);
if(op == 1) q[++qsz] = (Query){x, y, csz, qsz};
else {
y = compress(y);
c[++csz] = (Change){x, y, now[x]}, now[x] = y;
}
}
sort(q+1, q+1+qsz);
for(int i = 1; i <= qsz; ++i) {
while(T < q[i].t) go(c[T+1].pos, c[T+1].New), ++T;
while(T > q[i].t) go(c[T].pos, c[T].Old), --T;
while(l < q[i].l) add(a[l], -1), ++l;
while(l > q[i].l) add(a[l-1], 1), --l;
while(r < q[i].r) add(a[r+1], 1), ++r;
while(r > q[i].r) add(a[r], -1), --r;
ans[q[i].id] = get();
}
for(int i = 1; i <= qsz; ++i) cout << ans[i] << endl;
return 0;
}
最后
以上就是妩媚便当为你收集整理的CodeForces 940F - Machine Learning (带修莫队)的全部内容,希望文章能够帮你解决CodeForces 940F - Machine Learning (带修莫队)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复