0
点赞
收藏
分享

微信扫一扫

P1903 [国家集训队] 数颜色 / 维护队列

凛冬已至夏日未远 2022-05-01 阅读 63
c++

原题链接
带修莫队模板.
增加一维时间t.
需要注意:
1.排序第一关键字为l所在块编号,第二关键字为r所在块编号,第三关键字为t.
2.块的大小为cbrt(n*t), 即block = cbrt((double)n * max(1, nc));
3.对t处理时可交换原序列中颜色编号与该操作交换后的颜色编号.
代码如下:

#include <cstdio>
#include <cctype>
#include <cmath>
#include <algorithm>

using namespace std;

inline int read(){
    int res = 0, pdf = 0; char ch = getchar();
    while(!isdigit(ch)) pdf = ch == '-', ch = getchar();
    while(isdigit(ch)) res = (res<<3) + (res<<1) + (ch^48), ch = getchar();
    return pdf ? -res : res;
} 

inline void Print(int x) {
	if (x < 0) x = -x, putchar('-'); 
	if (x < 10) putchar(x + '0'); 
	else {
		Print(x / 10); 
		putchar(x % 10 + '0'); 
	}
} 

const int N = 2e6 + 10; 
int n, m, ans, nq, nc, block, pos[N], col[N], ton[N]; 
struct Query {
	int id, l, r, t, ans; 
}q[N];
struct Change {
	int p, k; 
}c[N]; 

bool cmp1(Query x, Query y) {
	if (pos[x.l] != pos[y.l]) return pos[x.l] < pos[y.l]; 
	if (pos[x.r] != pos[y.r]) return pos[x.r] < pos[y.r]; 
	return x.t < y.t; 
}

bool cmp2(Query x, Query y) {
	return x.id < y.id; 
}

void update(int p, int k) {
	ans -= ton[p] != 0; 
	ton[p] += k; 
	ans += ton[p] != 0; 
}

void Solve() {
	for (int i = 1, l = 1, r = 0, t = 0; i <= nq; ++i) {
		while (l < q[i].l) update(col[l++], -1); 
		while (l > q[i].l) update(col[--l], 1); 
		while (r < q[i].r) update(col[++r], 1); 
		while (r > q[i].r) update(col[r--], -1); 
		while (t < q[i].t) {
			++t; 
			if (c[t].p >= l && c[t].p <= r) {
				update(col[c[t].p], -1); 
				update(c[t].k, 1);  
			}
			swap(col[c[t].p], c[t].k); 
		}
		while (t > q[i].t) {
			if (c[t].p >= l && c[t].p <= r) {
				update(col[c[t].p], -1); 
				update(c[t].k, 1);  
			}
			swap(col[c[t].p], c[t].k); 
			--t; 
		}
		q[i].ans = ans; 
 	}
}

int main() {
	n = read(); m = read(); 
	for (int i = 1; i <= n; ++i) col[i] = read(); 
	for (int i = 1; i <= m; ++i) {
		char opt = getchar(); 
		while (opt != 'Q' && opt != 'R') opt = getchar(); 
		if (opt == 'Q') {
			int ll = read(), rr = read(); 
			q[++nq].id = nq; q[nq].l = ll; q[nq].r = rr; q[nq].t = nc; 
		} else {
			int pp = read(), kk = read(); 
			c[++nc].p = pp; c[nc].k = kk; 
		}
	}
	block = cbrt((double)n * max(1, nc)); 
	for (int i = 1; i <= n; ++i) pos[i] = i / block + 1; 
	sort(q + 1, q + nq + 1, cmp1); 
	Solve(); 
	sort(q + 1, q + nq + 1, cmp2); 
	for (int i = 1; i <= nq; ++i) {
		Print(q[i].ans); putchar('\n'); 
	}
	return 0; 
}
举报

相关推荐

0 条评论