分块套树状数组

· · 个人记录

分块套树状数组

应用

实现

初始化

查询

修改

e.g.CF1093E

对于每个值 i,记 x_i 为它在 b 中的下标,y_i 为它在 a 中的下标,这样操作一就变成了二维平面内矩阵区域内点个数查询,操作二可以看做两个修改。因为是排列满足 x_i \neq x_j,可以按照上述方法处理。

代码

# include <bits/stdc++.h>

using namespace std;

int read()
{
# define C ch = getchar()
    int x = 0; char C;
    for(; ch > '9' || ch < '0'; C); for(; ch >= '0' && ch <= '9'; C) x = (x << 3) + (x << 1) + (ch ^ 48);
    return x;
}

const int N = 2e5 + 5 , S = 500;
int n , m , a[N] , b[N];

struct block
{
    int c , L[N] , R[N] , blo[N];
    void init()
    {
        c = n / S;
        for(int i = 1; i <= c; i++) L[i] = R[i - 1] + 1 , R[i] = L[i] + S - 1;
        if(R[c] < n) c++ , L[c] = R[c - 1] + 1 , R[c] = n;
        for(int i = 1; i <= n; i++) blo[i] = (i - 1) / S + 1;
    }
} B;

struct BIT
{
    int tr[S][N];
    int Lowbit(int x) {return x & -x;}
    void Upt(int x , int y , int d)
    {
        for(int i = B.blo[x]; i <= B.c; i += Lowbit(i))
            for(int j = y; j <= n; j += Lowbit(j))
                tr[i][j] += d;
    }
    void Change(int x , int y)
    {
        Upt(x , b[x] , -1);
        Upt(y , b[y] , -1);
        swap(b[x] , b[y]);
        Upt(x , b[x] , 1);
        Upt(y , b[y] , 1);
    }
    int get(int x , int y)
    {
        if(!x) return 0;
        int res = 0 , p = B.blo[x];
        for(int i = B.L[p]; i <= x; i++) if(b[i] <= y) res++;
        for(int i = p - 1; i; i -= Lowbit(i))
            for(int j = y; j; j -= Lowbit(j))
                res += tr[i][j];
        return res;
    }
    int Query(int la , int ra , int lb , int rb)
    {
        return get(rb , ra) - get(rb , la - 1) - get(lb - 1 , ra) + get(lb - 1 , la - 1);
    }
} bit;

int main()
{
    n = read() , m = read();
    for(int i = 1 , x; i <= n; i++) x = read() , a[x] = i;
    for(int i = 1 , x; i <= n; i++) x = read() , b[i] = a[x];
    B.init();
    for(int i = 1; i <= n; i++) bit.Upt(i , b[i] , 1);
    for(int i = 1 , opt , la , ra , lb , rb , x , y; i <= m; i++)
    {
        opt = read();
        if(opt == 1)
        {
            la = read() , ra = read() , lb = read() , rb = read();
            cout << bit.Query(la , ra , lb , rb) << '\n';
        }
        else
        {
            x = read() , y = read();
            bit.Change(x , y);
        }
    }
    return 0;
}