二维树状数组入门题 poj2642Stars

题目连接:Stars

 题解:把一维的的树状数组扩展到二维就行,复杂度为o(mlog^2n)

#include<bits/stdc++.h>
#include<set>
#include<cstdio>
#include<iomanip>
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#define pb push_back
#define ll long long
#define fi first
#define se second
#define PI 3.14159265
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1
#define eps 1e-7
#define pii pair<int,int>
typedef unsigned long long ull;
const int mod=1e3+5;
const ll inf=0x3f3f3f3f3f3f3f;
const int maxn=1e3+5;
using namespace std;
int n,m,a[maxn][maxn];
bool vis[maxn][maxn];
int lower_bit(int x){return x&(-x);}
void add(int x,int y,int val)
{
    for(int i=x;i<maxn;i+=lower_bit(i))
    {
        for(int j=y;j<maxn;j+=lower_bit(j))
        {
            a[i][j]+=val;
        }
    }
}
int get_sum(int x,int y)
{
    int ans=0;
    while(x>0)
    {
        for(int j=y;j>0;j-=lower_bit(j))
        {
            ans+=a[x][j];
        }
        x-=lower_bit(x);
    }
    return ans;
}
int main()
{
   // ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
   // cin>>n;
    scanf("%d",&n);
    while(n--)
    {
        int x,y,x2,y2;char op[10];
       // cin>>op;
       scanf("%s",&op);
        if(op[0]=='B')
        {
            //cin>>x>>y;
            scanf("%d %d",&x,&y);x++;y++;
            if(!vis[x][y])add(x,y,1),vis[x][y]=1;
        }
        else if(op[0]=='D')
        {
            //cin>>x>>y;
            scanf("%d %d",&x,&y);x++,y++;
            if(vis[x][y])add(x,y,-1),vis[x][y]=false;
        }
        else
        {
            //cin>>x>>x2>>y>>y2;
            scanf("%d %d %d %d",&x,&x2,&y,&y2);x++;x2++,y2++;y++;
            if(x>x2)swap(x,x2);if(y>y2)swap(y,y2);
            printf("%d\n",get_sum(x2,y2)-get_sum(x-1,y2)-get_sum(x2,y-1)+get_sum(x-1,y-1));
           // cout<<get_sum(x2,y2)-get_sum(x-1,y2)+get_sum(x2,y-1)+get_sum(x-1,y-1)<<endl;
        }

    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lhclqslove/p/9352958.html
今日推荐