Stars(树状数组单点更新)

Posted moomcake

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stars(树状数组单点更新)相关的知识,希望对你有一定的参考价值。

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
5 5

Sample Output

1
2
1
1
0

Hint

This problem has huge input data,use scanf() instead of cin to read data to avoid time limit exceed。
题意:有n个星星,每个星星都有一个二维坐标,在它的左下方有几个星星有几个就代表该星星属于第几级星星,求0-n-1级星星各有多少个,举个例子:第5个星星的坐标(5,5),第一,四,二个星星在他的左下方,所以该星星属于3级星星。
题解:将星星按照横坐标从小到大,纵坐标从小到大的顺序排序,这样之后判断该星星属于第几级只需要判断在它之前有几个横坐标比他小的星星就可以了,可以用树状数组来实现前缀和的、功能。
 1 #include <cstdio>
 2 #include <cstring>
 3 const int MAXN=1e5+10;
 4 int c[MAXN],a[MAXN];//a[]是哈希数数组,用来统计每个等级的数量
 5 int m,t;
 6 int Lowbit(int x)
 7 {
 8     return x&(-x);
 9 }
10 void update(int i, int x)//向上更新
11 {
12     while(i <= 100000)
13     {
14         c[i] += x;
15         i += Lowbit(i);
16     }
17 }
18 int Getsum(int x)//向下求和
19 {
20     int sum=0;
21     while(x>0)
22     {
23         sum+=c[x];
24         x-=Lowbit(x);
25     }
26     return sum;
27 }
28 int main()
29 {
30     int m,x,b;
31     while(scanf("%d",&m)!=-1)
32     {
33         int k=m;
34         memset(a,0,sizeof(0));
35         memset(c,0,sizeof(0));
36         while(k--)
37         {
38             scanf("%d%d",&x,&b);
39             a[Getsum(x+1)]++;//用getsome()来计算在该星星前有多少个星星即是它的等级,a[]是哈希数组
40             update(x+1,1);//把该点更新
41         }
42         for(int i=0; i<m; i++)
43         {
44             printf("%d
",a[i]);
45         }
46     }
47     return 0;
48 }

 

以上是关于Stars(树状数组单点更新)的主要内容,如果未能解决你的问题,请参考以下文章

树状数组从入门到弃疗

树状数组模板(持续更新)

[POJ2352] Stars(树状数组)

(二维树状数组)E - Stars

树状数组区间更新

HDU-1754 I Hate It (树状数组模板题——单点更新,区间查询最大值)