您的位置:首页 > 其它

poj 1656(二维树状数组解法)

2012-05-06 18:06 281 查看
题目信息:count black

利用二维树状数组:

//利用二维树状数组
#include<iostream>
#include<string>
#include<cstring>
using namespace std;

int c[101][101];
int b[101][101];
int Row,Col;

//下面三个函数是基本套路
inline int Lowbit(const int &x)
{
return x&(-x);
}

int Sum(int i,int j)
{//计算(1,1)--(i,j)之间的和
int tempj,sum=0;
while(i > 0)
{
tempj=j;
while(tempj > 0){
sum+=c[i][tempj];
tempj-=Lowbit(tempj);
}
i-=Lowbit(i);
}
return sum;
}

void Update(int i,int j,int num)
{//更新(i,j) 为c[i][j]+num
int tempj;
while(i<=Row)
{
tempj=j;
while(tempj<=Col){
c[i][tempj]+=num;
tempj+=Lowbit(tempj);
}
i+=Lowbit(i);
}
}

void whiteUpdate(int x,int y,int L)
{
for(int i=x;i<x+L;++i)
for(int j=y;j<y+L;++j)
{
if(b[i][j]==1) {b[i][j]=0;Update(i,j,-1);}
else continue;
}
}

void blackUpdate(int x,int y,int L)
{
for(int i=x;i<x+L;++i)
for(int j=y;j<y+L;++j)
{
if(b[i][j]==1) continue;
else {b[i][j]=1;Update(i,j,1);};
}
}

int blackSum(int x,int y,int L)
{//计算(x,y)--(x+L-1,Y+L-1)之间的数
return Sum(x+L-1,y+L-1)+Sum(x-1,y-1)-Sum(x-1,y+L-1)-Sum(x+L-1,y-1);
}

int main()
{
int x,y,L,N;
string str;
Row=Col=100;
memset(c,0,sizeof(c));
memset(b,0,sizeof(b));
cin>>N;
while(N--)
{
cin>>str>>x>>y>>L;
switch(str[0])
{
case 'W':
whiteUpdate(x,y,L);
break;
case 'B':
blackUpdate(x,y,L);
break;
case 'T':
cout<<blackSum(x,y,L)<<endl;
break;
default: break;
}
}
return 0;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: