Tree array statistics

Tree array summary

Tree array, use Θ (log ⁡ n) \Theta(\log n)Θ ( lo gn ) time to solve the prefix sum and add a[x] to a number. It can be done with a tree array if and only if the problem can be converted to the above two operations.

1. Modify a number

void add(int x,int y)
{
    
    
    while(x<=n)//在树上所包含的所有集合
    {
    
    
        tree[x]+=y;
		x+=lowbit(x);
    }
}

2. Find the prefix sum

int get(int x)
{
    
    
    int sum=0;
    while(x)//把一条链分成几段加起来
    {
    
    
		sum+=tree[x];
		x-=lowbit(x);
    }
    return sum;
}

Deformation of tree array

1. Find the reverse order

for(int i=1;i<=n;i--)
{
    
    
    s[i]=i-1-get(a[i]);//比a[i]小的,用总的减小的,别忘记减掉自己的1
    add(a[i],1);
}

2. Two-dimensional tree array

void add(int x,int y,int z)
{
    
    
    while(x<=n)
    {
    
    
		int i=y;
		while(i<=m)
		{
    
    
	    	tree[x][i]+=z;
	    	i+=lower(i);
		}
		x+=lower(x);
    }
}
int get(int x,int y)
{
    
    
    int sum=0;
    while(x>0)
    {
    
    
		int i=y;
		while(i>0)
		{
    
    
	   		sum+=tree[x][i];
	    	i-=lower(i);
		}
		x-=lower(x);
    }
    return sum;
}

Guess you like

Origin blog.csdn.net/weixin_44043668/article/details/106591704