树状数组的原理和实现
概念
C1 = A1 C2 = A1+A2 C3 = A3 C4 = A1+A2+A3+A4 C5 = A5 C6 = A5+A6 C7 = A7 C8 = A1+A2+A3+A4+A5+A6+A7+A8
原理
lowbit
def LOWBIT(x):
return x & (-x)
单点修改
def MODIFY(x, delta):
if x < 1:
return
while x <= n:
fenwick[x] += delta
x += LOWBIT(x)
查询
def QUERY(x):
result = 0
while right > 0:
result += fenwick[x]
x -= LOWBIT(x)
return result
练习
#include<stdio.h>
#include<string.h>
int c[32000+10];
int a[15000+10];
int lowbit(int x)
{
return x&(-x);
}
void updata(int x,int d)
{
while(x<=32001)
{
c[x]=c[x]+d;
x=x+lowbit(x);
}
}
int getsum(int x)
{
int res = 0;
while(x>0)
{
res=res+c[x];
x=x-lowbit(x);
}
return res;
}
int main()
{
int n;
int i,x,y;
while(scanf("%d",&n)!=EOF)
{
memset(c,0,sizeof(c));
memset(a,0,sizeof(a));
for(i=0; i<n; i++)
{
//因为y是升序,所以横坐标小于x的,(想了很久)所有点都符合,这是解这道题的关键。
scanf("%d%d",&x,&y); //下标可能从0开始,所以要x+1
a[getsum(x+1)]++; //求出横坐标小于x的所有stars个数,并记录到a中
updata(x+1,1); //更新区间
}
for(i=0; i<n; i++)
{
printf("%d\n",a[i]);
}
}
return 0;
}
优缺点
来源:https://www.cnblogs.com/George1994/p/7710886.html