bzoj 2120 : 数颜色 分块
给一个序列, 两种操作, 一种是将x位置的数改为y, 一种是询问[l, r]之间有多少种不同的数, 数的范围<1e6。
分块, 对于每个数, 记录它前面的和他相同的数的位置, 如果pre[i]<l, 那么ans++, 具体看代码......
#include <iostream> #include <vector> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <map> #include <set> #include <string> #include <queue> #include <stack> #include <bitset> using namespace std; #define pb(x) push_back(x) #define ll long long #define mk(x, y) make_pair(x, y) #define lson l, m, rt<<1 #define mem(a) memset(a, 0, sizeof(a)) #define rson m+1, r, rt<<1|1 #define mem1(a) memset(a, -1, sizeof(a)) #define mem2(a) memset(a, 0x3f, sizeof(a)) #define rep(i, n, a) for(int i = a; i<n; i++) #define fi first #define se second typedef pair<int, int> pll; const double PI = acos(-1.0); const double eps = 1e-8; const int mod = 1e9+7; const int inf = 1061109567; const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; int n, m, block, q, a[10005], b[1000005], last[1000005], pre[1000005], pos[10005]; void reset(int x) { int l = (x-1)*block+1, r = min(x*block, n); for(int i = l; i<=r; i++) { pre[i] = b[i]; } sort(pre+l, pre+r+1); } void build() { for(int i = 1; i<=n; i++) { b[i] = last[a[i]]; last[a[i]] = i; pos[i] = (i-1)/block+1; } for(int i = 1; i<=m; i++) reset(i); } void update(int p, int val) { for(int i = 1; i<=n; i++) { last[a[i]] = 0; } a[p] = val; for(int i = 1; i<=n; i++) { int t = b[i]; b[i] = last[a[i]]; if(t != b[i]) reset(pos[i]); last[a[i]] = i; } } int find(int x, int pos) { int l = (x-1)*block+1, r = min(n, x*block); int first = l; while(l<=r) { int mid = l+r>>1; if(pre[mid]<pos) l = mid+1; else r = mid-1; } return l-first; } int query(int l, int r) { int ans = 0; if(pos[l] == pos[r]) { for(int i = l; i<=r; i++) { if(b[i]<l) ans++; } } else { for(int i = l; i<=(block*pos[l]); i++) { if(b[i]<l) ans++; } for(int i = block*(pos[r]-1)+1; i<=r; i++) { if(b[i]<l) ans++; } } for(int i = pos[l]+1; i<pos[r]; i++) ans += find(i, l); return ans; } int main() { scanf("%d%d", &n, &q); for(int i = 1; i<=n; i++) scanf("%d", &a[i]); block = (int)(sqrt(n)+log(2*n)/log(2)); if(n%block) m = n/block+1; else m = n/block; build(); char ch; int x, y; while(q--) { scanf(" %c%d%d", &ch, &x, &y); if(ch == 'Q') { printf("%d\n", query(x, y)); } else { update(x, y); } } return 0; }