当前位置: 代码迷 >> 综合 >> POJ 2352 Stars【树状数组】
  详细解决方案

POJ 2352 Stars【树状数组】

热度:73   发布时间:2023-12-16 05:57:54.0

题目

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.

题目大意

给定一些星星在二维平面中的坐标并给星星赋予等级,星星的等级为除了自身以外的所有横纵坐标不大于自身的星星数量。如图中有0级星星1颗,1级星星2颗,2级星星1颗,3级星星1颗。数据按照y轴升序给出,y轴坐标相同时,按x轴大小升序给出,输入数据较多,采用scanf读入数据。
输出各级星星数量。

input

The first line of the input file contains a number of stars N ( 1 ≤ N ≤ 15000 ) N (1\le N\le15000) N(1N15000). The following N lines describe coordinates of stars (two integers X and Y per line separated by a space, 0 ≤ X , Y ≤ 32000 0\le X,Y\le32000 0X,Y32000). 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

分析

本题在题目中说明了,数据按照y轴升序给出,那么我们可以选择直接计算在x轴递增的情况下,前x个数据的前缀和,因为后续的数据标注的星星位置一定不会符合之前星星定级的条件。采用树状数组的方式,实现查询前缀和与点更新操作。
注意:给出的点位置x轴坐标从0开始,但是树状数组的下标只能从1开始,因此需要对每一次输入的x值进行+1处理。
树状数组的原理与实现

代码

#include<iostream>
using namespace std;
typedef long long ll;
int a[32010],star[15010];
int lowbit(int x){
    //最低位1查询return (-x)&x;
}
int getsum(int x){
    //查询前缀和int ans = 0;while(x>0){
    ans+=a[x];x-=lowbit(x);}return ans;
}
void add(int x,int val){
    //点更新while(x<=32001){
    //32001为最大的x范围(+1)a[x]+=val;x+=lowbit(x);}
}
int main(){
    int n,x,y;scanf("%d",&n);for(int i=0;i<n;++i){
    scanf("%d %d",&x,&y);x++;star[getsum(x)]++;add(x,1);}for(int i = 0;i<n;++i) printf("%d\n",star[i]);return 0;
}