【原】 POJ 2352 Stars 树状数组 解题报告
http://poj.org/problem?id=2352
方法:复杂度N*O(log Max)
树状数组Binary Indexed Tree,具体见3321
求得常变二维平面上(0,0)到(x,y)所形成的矩形中点的个数
由于内存限制,所以只能考虑用一维的BIT来解决此问题。因此需要将输入数据先按y排序,再对
同y的x排序,对这样排序好的数据依次进行处理。(题目中已经排好序)
每输入一个数据(x1,y1),即更新tree[x1...Max],同时求和GetSum(x1)。不用考虑y1,因为此时
已经得到的二维图中所有点的y都小于等于y1,所以只需要考虑x小于等于x1的点即可。这都是由于
对数据排序的结果
注意:
1、不能用2D的BIT:int tree[Max+1][Max+1]。那样会超过内存限制
2、一定要注意BIT的最大索引的范围。将Max设置为32002,定义int tree[Max]造成了无数WA
3、由于此数据会用到索引0,不符合BIT不用0的要求,所以可以将所有索引值+1
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
1: #include <stdio.h>
2:
3: const int Max = 32001 ;
4: const int N = 15001 ;
5:
6: int tree[Max+1] = {0} ; //****
7: int level[N] = {0} ;
8:
9: int GetSum( int idx )
10: {
11: int sum = 0 ;
12: while( idx>0 )
13: {
14: sum += tree[idx] ;
15: idx -= ( idx & -idx ) ;
16: }
17: return sum ;
18: }
19:
20: void AddVal( int idx, int val )
21: {
22: while( idx<=Max )
23: {
24: tree[idx] += val ;
25: idx += ( idx & -idx );
26: }
27: }
28:
29: void BuildBIT( int n )
30: {
31: int x,y ;
32: for( int i=0 ; i<n ; ++i )
33: {
34: scanf( "%d%d", &x,&y ) ;
35: ++x ; //避免x=0的情况
36: AddVal( x , 1 ) ;
37: ++level[ GetSum(x)-1 ] ;
38: }
39: }
40:
41: void run2352()
42: {
43: int n ;
44:
45: scanf( "%d", &n ) ;
46:
47: BuildBIT( n ) ;
48: for( int i=0 ; i<=n-1 ; ++i )
49: printf( "%d\n", level[i] ) ;
50: }