【bzoj2453】维护队列 (分块 + 二分)

传送门(权限题)

题目分析

题意为:求区间内有多少种不同的数,带修改。 首先对原序列分块,用last[i]表示与i相同的上一个在哪里,然后将分块后的数组每个块内的按照last进行排序,这样查询时就可以暴力枚举散块,看last[i]是否<l,是则ans++,并二分枚举每个整块,查找出last < l 的数的个数即新出现的数。对于修改,修改后暴力重新构建被影响点所在的块。

code

3452 ms

#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;
}
posted @ 2017-08-19 16:55  CzYoL  阅读(187)  评论(0编辑  收藏  举报