1. 程式人生 > 其它 >P2464 [SDOI2008] 鬱悶的小 J 題解

P2464 [SDOI2008] 鬱悶的小 J 題解

簡單分塊。

用一個 map 來維護每塊裡的出現次數就行了。


/*
	Work by: TLE_Automation
*/
#include<map>
#include<cmath>
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<tr1/unordered_map>
#define LL long long
// #define int long long
using namespace std;
using namespace std::tr1;

const int N = 1e6 + 10;
const int MAXN = 2e5 + 10;

inline char readchar() {
	static char buf[100000], *p1 = buf, *p2 = buf;
	return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 100000, stdin), p1 == p2) ? EOF : *p1++;
}

inline int read() {
#define readchar getchar
	int res = 0, f = 0;char ch = readchar();
	for(; !isdigit(ch); ch = readchar()) if(ch == '-') f = 1;
	for(; isdigit(ch); ch = readchar()) res = (res << 1) + (res << 3) + (ch ^ '0');
	return f ? -res : res;
}

inline void print(int x) {
	if (x < 0 ) putchar('-'), x = -x;
	if (x > 9 ) print(x / 10);
	putchar(x % 10 + '0');
}
int n, Q, a[MAXN], bel[MAXN], l[MAXN], r[MAXN], num;
unordered_map <int, int> Block[1005];

void build() {
	int len = n / num;
	for(register int i = 1; i <= num; i++) {
		l[i] = len * (i - 1) + 1;
		r[i] = len * i; 
	}
	r[num] = n;
	for(register int i = 1; i <= num; i++) {
		for(register int j = l[i]; j <= r[i]; j++) {
			bel[j] = i; Block[i][a[j]]++;
		}
	}
}

int Query(int x, int y, int k) {
	int res = 0;
	if(bel[x] == bel[y]) {
		for(register int i = x; i <= y; i++) res += (a[i] == k);
		return res;
	}
	for(register int i = x; i <= r[bel[x]]; i++) res += (a[i] == k);
	for(register int i = l[bel[y]]; i <= y; i++) res += (a[i] == k);
	for(register int i = bel[x] + 1; i < bel[y]; i++) res += Block[i][k];
	return res;
}

signed main() {
	n = read(), Q = read();
	num = sqrt(n);
	for(int i = 1; i <= n; i++) a[i] = read();
	build();
	for(int i = 1, l, r, x; i <= Q; i++) {
		char opt; cin >> opt;
		if(opt == 'Q') l = read(), r = read(), x = read(), printf("%d\n", Query(l, r, x));
		else {
			l = read(), r = read();
			Block[bel[l]][a[l]]--;
			a[l] = r;
			Block[bel[l]][a[l]]++;
		}
	}
}