区间信息的查询与维护(一)树状树组

来源:互联网 发布:康熙王朝 知乎 编辑:程序博客网 时间:2024/06/05 23:03
区间信息的查询与维护(一)树状树组
 核心代码:
int lowbit(int x)
{
 return x&-x;
}
int sum(int x)
{
 int ret=0;
 while(x>0)
 {
  ret+=c[x];
  x-=lowbit(x);
 }
return ret;
}
void add(int x,int d)
{
 while(x<=n)
 {
  c[x]+=d;
  x+=lowbit(x);
 }
}
 其中 x-lowbit(x)代表右子节点的父节点,x+lowbit(x)代表左子节点的父节点。
sum(i)用于求前i项的和,add(int x,int d)用于修改节点信息。
它的修改与求和都是O(logn)的,效率非常高。



典型应用
例题一
LA 4392   POJ

Description

N(3<=N<=20000) ping pong players live along a west-east street(consider the street as a line segment). Each player has a unique skill rank. To improve their skill rank, they often compete with each other. If two players want to compete, they must choose a referee among other ping pong players and hold the game in the referee's house. For some reason, the contestants can't choose a referee whose skill rank is higher or lower than both of theirs. The contestants have to walk to the referee's house, and because they are lazy, they want to make their total walking distance no more than the distance between their houses. Of course all players live in different houses and the position of their houses are all different. If the referee or any of the two contestants is different, we call two games different. Now is the problem: how many different games can be held in this ping pong street?

Input

The first line of the input contains an integer T(1<=T<=20), indicating the number of test cases, followed by T lines each of which describes a test case. 
Every test case consists of N + 1 integers. The first integer is N, the number of players. Then N distinct integers a1, a2 ... aN follow, indicating the skill rank of each player, in the order of west to east. (1 <= ai <= 100000, i = 1 ... N).

Output

For each test case, output a single line contains an integer, the total number of different games. 

Sample Input

1 3 1 2 3

Sample Output
1

代码:

#include <iostream>
  #include <cstdio>
  #include <cstdlib>
  #include <cstring> 
 #define lowbit(x) ((x)&(-(x)))
 using namespace std;
 const int max_a=100000+1000;
 const int max_num=20000+200;
typedef long long LL;
int a[20000+200];
LL cc[20000+200],dd[20000+200];
 int n=max_a,C[max_a];

 int sum(int x) {
     int ret = 0;
     while ( x>0 ) {
         ret += C[x];
         x -= lowbit(x);
     }
    return ret;
 }
 
 void add(int x, int d) {
     while(x <= n) {
         C[x] += d;
         x += lowbit(x);
     }
 }
  int main()
 {
     //freopen("input.txt","r",stdin);
     int T;cin>>T;
     int num;
     for(int tt=1;tt<=T;tt++) {
         scanf("%d",&num);
         for(int i=0;i<num;i++)
             scanf("%d",&a[i]);
 

         memset(C,0,sizeof(C));
         for(int i=0;i<num;i++) {
             add(a[i],1);
             cc[i]=sum(a[i])-1;//cout<<cc[i]<<endl;
         }
         memset(C,0,sizeof(C));
         for(int i=num-1;i>=0;i--) {
             add(a[i],1);
             dd[i]=sum(a[i])-1;//cout<<cc[i]<<endl;
         }
         long long ans=0;
         for(int i=1;i<num-1;i++) {
             ans+=(cc[i])*(num-(1+i)-dd[i])+
                  (i-cc[i])*(dd[i]);
         }
         cout<<ans<<endl;
     }
     return 0;
 }


其中
for(int i=0;i<num;i++) {
             add(a[i],1);
             cc[i]=sum(a[i])-1;//cout<<cc[i]<<endl;
         }      
可以求出比a[i]小的数的个数
   for(int i=num-1;i>=0;i--) {
             add(a[i],1);
             dd[i]=sum(a[i])-1;//cout<<cc[i]<<endl;
         } 
可以求出比a[i]大的数的个数 


例题二
POJ2352

Stars
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 27339 Accepted: 11959

Description

Astronomers often examine star maps where stars are represented by points on a plane and each star has Cartesian coordinates. Let the level of a star be an amount of the stars that are not higher and not to the right of the given star. Astronomers want to know the distribution of the levels of the stars. 

For example, look at the map shown on the figure above. Level of the star number 5 is equal to 3 (it's formed by three stars with a numbers 1, 2 and 4). And the levels of the stars numbered by 2 and 4 are 1. At this map there are only one star of the level 0, two stars of the level 1, one star of the level 2, and one star of the level 3. 

You are to write a program that will count the amounts of the stars of each level on a given map.

Input

The first line of the input file contains a number of stars N (1<=N<=15000). The following N lines describe coordinates of stars (two integers X and Y per line separated by a space, 0<=X,Y<=32000). There can be only one star at one point of the plane. Stars are listed in ascending order of Y coordinate. Stars with equal Y coordinates are listed in ascending order of X coordinate. 

Output

The output should contain N lines, one number per line. The first line contains amount of stars of the level 0, the second does amount of stars of the level 1 and so on, the last line contains amount of stars of the level N-1.

Sample Input
5
1 1
5 1
7 1
3 3
5 5 

Sample Output

1
2
1
1
0

题目大意
在一个坐标系内,给若干个点,每个点给定xy坐标,定义点plevel为横纵坐标均不超过点p的点的个数,输出每个level包含的点的数量。

解题思路

         这道题目和计数有关,是典型的树状数组应用的题目。题目给的数据按照y排序,相同的y按照x排序,这就给解题带来了很大的方便,我们可以按照由下至上、由左至右的顺序来处理数据,这样我们只利用x就可以进行计数了,因为当我们处理到任意点p的时候,所有的y小于p的点我们已经计数过了,只需要统计所有x不超过p的点的数量就可以了,而这一步利用树状数组强大的计数功能实现。

         sum[i]表示x不大于i的点的数目,每次统计完i的数目后,要把sum[i]计数增加1



代码
#include<stdio.h>
#include<string.h>
const int n=50000;
int c[50000];
int lowbit(int x)
{
 return x&-x;
}
int sum(int x)
{
 int ret=0;
 while(x>0)
 {
  ret+=c[x];
  x-=lowbit(x);
 }
 return ret;
}
void add(int x,int d)
{
 while(x<=n)
 {
  c[x]+=d;
  x+=lowbit(x);
 }
}

void main()
{
 int m,cc[50000],x,y,i;
 while(scanf("%d",&m)!=EOF)
 {
  memset(cc,0,sizeof(cc)); 
  memset(c,0,sizeof(c));
  for( i=0;i<m;i++)
  {
   scanf("%d%d",&x,&y);
   cc[sum(x+1)]++;
   add(x+1,1);
  
  } 
  for(i=0;i<m;i++)
   printf("%d\n",cc[i]);
 }
}

例三
HDU 1556

Color the ball

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6279    Accepted Submission(s): 3334


Problem Description
N个气球排成一排,从左到右依次编号为1,2,3....N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽"牌电动车从气球a开始到气球b依次给每个气球涂一次颜色。但是N次以后lele已经忘记了第I个气球已经涂过几次颜色了,你能帮他算出每个气球被涂过几次颜色吗?
 


Input
每个测试实例第一行为一个整数N,(N <= 100000).接下来的N行,每行包括2个整数a b(1 <= a <= b <= N)。
当N = 0,输入结束。
 


Output
每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。
 


Sample Input
31 12 23 331 11 21 30
 


Sample Output
1 1 13 2 1


#include<stdio.h>
#include<string.h>
const int n=100000;
int c[100000];
int lowbit(int x)
{
 return x&-x;
}

int sum(int x)
{
 int ret=0;
 while(x>0)
 {
  ret+=c[x];
  x-=lowbit(x);
 }
 return ret;
}

void add(int x,int d)
{
 while(x<=n)
 {
  c[x]+=d;
  x+=lowbit(x);
 }
}


void main()
{
 int n1,n,x,y,i;
 while(scanf("%d",&n),n)
 {
  memset(c,0,sizeof(c));
  n1=n;
  while(n--)
  {
   scanf("%d%d",&x,&y);
   add(x,1);
   add(y+1,-1);
  }
  for(i=1;i<n1;i++)
  {
   printf("%d ",sum(i));
  }
  printf("%d\n",sum(i));
 }
}

本来主函数我是这样写的:
void main()
{

    int
 n1,n,x,y,i; while(scanf("%d",&n),n)
    {

        memset(c,0,sizeof(c));
        n1=n;
        while
(
n--)
        {

            scanf("%d%d",&x,&y);
            for
(
i=x;i<=y;i++)
                add(i,1);
        }

        for
(
i=1;i<n1;i++)
        {

            printf("%d ",sum(i)-sum(i-1));
        }

        printf("%d\n",sum(i)-sum(i-1));
    }
}
但是出现了超时的情况
Time Limit Exceeded
 
add(x,1);
   add(y+1,-1);
可以代替for循环,是一个不错的技巧,嘿嘿,直接降到了390MS 
 
 

 

原创粉丝点击