【bzoj2453】维护队列 (分块 + 二分)
传送门(权限题)
题目分析
题意为:求区间内有多少种不同的数,带修改。 首先对原序列分块,用last[i]表示与i相同的上一个在哪里,然后将分块后的数组每个块内的按照last进行排序,这样查询时就可以暴力枚举散块,看last[i]是否<l,是则ans++,并二分枚举每个整块,查找出last < l 的数的个数即新出现的数。对于修改,修改后暴力重新构建被影响点所在的块。
code
3452 ms
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<cmath> #include<string> #include<algorithm> #include<vector> using namespace std; const int N = 1e4 + 50; int n, m, col[N], now[1000005], last[N], La[N], S, blo; inline int read(){ int i = 0, f = 1; char ch = getchar (); for (; (ch < '0' || ch > '9' ) && ch != '-' ; ch = getchar ()); if (ch == '-' ) f = -1, ch = getchar (); for (; ch >= '0' && ch <= '9' ; ch = getchar ()) i = (i << 3) + (i << 1) + (ch - '0' ); return i * f; } inline void wr( int x){ if (x < 0) putchar ( '-' ),x = -x; if (x > 9) wr(x / 10); putchar (x % 10 + '0' ); } inline void change( int x, int c){ if (col[x] == c) return ; for ( int i = 1; i <= n; i++) now[col[i]] = 0; col[x] = c; for ( int i = 1; i <= n; i++){ int tmp = last[i]; last[i] = now[col[i]]; if (last[i] != tmp){ int B = i / S + (i % S ? 1 : 0); int l = (B - 1) * S + 1, r = min(n, B * S); for ( int j = l; j <= r; j++) La[j] = last[j]; sort(La + l, La + r + 1); } now[col[i]] = i; } } inline int query( int x, int y){ int ans = 0; if (y - x + 1 <= 2 * S){ for ( int i = x; i <= y; i++) if (last[i] < x) ans++; return ans; } int Bx = x / S + (x % S ? 1 : 0), By = y / S + (y % S ? 1 : 0); int L = Bx + 1, R = By - 1; if (x == (Bx - 1) * S + 1) L--; if (y == min(n, By * S)) R++; for ( int i = x; i <= (L - 1) * S; i++) if (last[i] < x) ans++; for ( int i = min(n, R * S) + 1; i <= y; i++) if (last[i] < x) ans++; for ( int i = L; i <= R; i++){ int l = (i - 1) * S + 1, r = min(n, i * S); int tmp = lower_bound(La + l, La + r + 1, x) - (La + l); ans += tmp; } return ans; } int main(){ n = read(), m = read(), S = 200, blo = n / S + (n % S ? 1 : 0); for ( int i = 1; i <= n; i++){ col[i] = read(); last[i] = La[i] = now[col[i]]; now[col[i]] = i; } for ( int i = 1; i <= blo; i++){ int l = (i - 1) * S + 1, r = min(n, i * S); sort(La + l, La + r + 1); } for ( int i = 1; i <= m; i++){ char opt[5]; scanf ( "%s" , opt + 1); if (opt[1] == 'Q' ){ int l = read(), r = read(); if (l > r) swap(l, r); wr(query(l, r)), putchar ( '\n' ); } else if (opt[1] == 'R' ){ int x = read(), c = read(); change(x, c); } } return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步