标签:des blog http java strong 数据
跟着大一新生的培训项目,看到树状数组,自己也是一年前学的了,就看了一下,马上就理解了
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 39849 Accepted Submission(s): 16819

int Lowbit(int x)
{
return x&(-x);
}
这个函数在1--10的输出结果,我打印出来了
1 2 1 4 1 2 1 8 1 2
就是求解相加的有多少项
n 1 2 3 4 5 6 7 8 9 10
lowbit 1 2 1 4 1 2 1 8 1 2
C1=A1 C2= C3= C4= C5= C6= C7= C8= ……
A1+A2 A3 A1+A2+ A5 A5+A6 A7 A1+A2+
A3+A4 A3+A4+A5+A6+A7+A8
Lowbit的解正好算出了Ci 应该加的项数
void Update(int x,int i)
{
while(x<=n)
{
c[x]+=i;
x+=Lowbit(x);
}
}
Update函数就是更新节点的值,就是把所有与x相关的值全部更新
比如此题:
当我输入10个数时相应的C【i】的值变化:
输入1 1 1 0 1 0 0 0 1 0 0 //相应C[1],C[2],C[4],C[8]变化
输入2 1 3 0 3 0 0 0 3 0 0
输入3 1 3 3 6 0 0 0 6 0 0
输入4 1 3 3 10 0 0 0 10 0 0
输入5 1 3 3 10 5 5 0 15 0 0
……
int Sum(int x)
{
int s=0;
while(x>0)
{
s+=c[x];
x-=Lowbit(x);
}
return s;
}
相加操作,利用前面求出的C[i]快速求出区间内的Sum值
具体自己在纸上一步步模拟。。。。。。
贴出自己的代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#define Maxx 50005
int c[Maxx];
int n;
int Lowbit(int x)
{
return x&(-x);
}
void Update(int x,int i)
{
while(x<=n)
{
c[x]+=i;
x+=Lowbit(x);
}
}
int Sum(int x)
{
int s=0;
while(x>0)
{
s+=c[x];
x-=Lowbit(x);
}
return s;
}
int main()
{
int t,i,j,m,a,b;
scanf("%d",&t);
int cas=1;
while(t--)
{
memset(c,0,sizeof(c));
//cas++;
printf("Case %d:\n",cas++);
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&m);
Update(i,m);//for(int j=1;j<=n;j++)printf("%d ",c[j]);
}
char str[10];
while(scanf("%s",str)!=EOF&&str[0]!=‘E‘)
{
scanf("%d%d",&a,&b);
if(str[0]==‘Q‘)
{
printf("%d\n",Sum(b)-Sum(a-1));
}
else if(str[0]==‘A‘)
{
Update(a,b);
}
else if(str[0]==‘S‘)
{
Update(a,-b);
}
}
}
return 0;
}
hdu 1166 敌兵布阵(树状数组),布布扣,bubuko.com
标签:des blog http java strong 数据
原文地址:http://www.cnblogs.com/ccccnzb/p/3836261.html