JSOI2009 Count

本文介绍了一种使用二维树状数组(Binary Indexed Tree, BIT)解决BZOJ平台上特定问题的方法。针对N、M、C较小的情况,通过为每种颜色分配独立的二维BIT进行维护,并利用前缀和技巧快速查询区间内的颜色出现次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BZOJ

我们可以发现\(N,M,C\)都十分的小,那么只要开很多个二维BIT来维护就可以了。每种颜色对应一个BIT。

然后查询的时候再用前缀和的思想来搞搞就可以了。

开始在BZOJ时候是T了的,后来才发现是BIT开太大了,导致寻址过慢。get一个新的卡常底层优化技巧

#include <bits/stdc++.h>

const int max_n=300+5;

int N,M,Q;
int A[max_n][max_n],bit[101][max_n][max_n];

inline int read()
{
    register int x=0;
    register char ch=getchar();
    while(!isdigit(ch))
        ch=getchar();
    while(isdigit(ch))
    {
        x=(x<<1)+(x<<3)+ch-'0';
        ch=getchar();
    }
    return x;
}

void modify(int c,int x,int y,int num)
{
    for(int i=x;i<=N;i+=i&-i)
        for(int j=y;j<=M;j+=j&-j)
            bit[c][i][j]+=num;
}

int query(int c,int x,int y)
{
    int res=0;
    for(int i=x;i;i-=i&-i)
        for(int j=y;j;j-=j&-j)
            res+=bit[c][i][j];
    return res;
}

int main()
{
    int opt,x,y,xt,yt,c;
    N=read(),M=read();
    for(int i=1;i<=N;++i)
    {
        for(int j=1;j<=M;++j)
        {
            A[i][j]=read();
            modify(A[i][j],i,j,1);
        }
    }
    Q=read();
    while(Q--)
    {
        opt=read();
        if(opt==1)
        {
            x=read(),y=read(),c=read();
            if(A[x][y]==c) continue;
            modify(A[x][y],x,y,-1);
            A[x][y]=c; 
            modify(A[x][y],x,y,1);
        }
        else
        {
           x=read(),xt=read(),y=read(),yt=read(),c=read();
           printf("%d\n",query(c,xt,yt)-query(c,xt,y-1)-query(c,x-1,yt)+query(c,x-1,y-1));
        }
    }
    return 0;
}

转载于:https://www.cnblogs.com/zcdhj/p/8324870.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值