HDU 1541 star (树状数组)

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.
天文学家经常研究星图,星图上的星星由平面上的点表示,每颗星星都有笛卡尔坐标。一颗星星的等级是指该星星左下方的星星的数量.
例如,查看上图所示的地图,5号星的等级为3(左下方有1、2、4号星),2号星和4号星的等级为1。在这张地图上有一颗0级的星星,两颗1级的星星,一颗2级的星星,和一颗3级的星星。 你需要写一个程序来计算给定星图上每个等级的星星数量
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.
输入的第一行包括了星星的数量N (1<=N<=15000),下面N行描述了每颗星星的坐标(每一行由一个空格分隔两个整数X和Y组成, 0<=X,Y<=32000)。每一个点只会存在一颗星星。星星以Y坐标的升序排列。Y坐标相等的恒星按X坐标的升序排列。
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.
输出应该包括N行,每行一个数字。第一行为等级是0级的星星数量,第二行为等级是1级的星星数量,以此类推,最后一行为等级是N-1级的星星数量。
Sample Input
5
1 1
5 1
7 1
3 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.


解题思路:这是一个树状数组的模板题,输入Y坐标是从小到大排序的,所以用数组记录横坐标就行了。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define lowbit(i) ((i)&(-i))
const int maxn=32005;
int c[maxn],a[maxn],n;
void update(int x,int v)//建树
{
    for(int i=x;i<maxn;i+=lowbit(i)){
        c[i]+=v;
    }
}
int getsum(int x)//查询
{
    int sum=0;
    for(int i=x;i>0;i-=lowbit(i)){
        sum+=c[i];
    }
    return sum;
}
int main()
{
    int x,y;
    while(~scanf("%d",&n))
    {
        memset(c,0,sizeof(c));
        memset(a,0,sizeof(a));
        for(int i=0; i<n; i++)
        {
            scanf("%d%d",&x,&y);
            x++;
            a[getsum(x)]++;
            update(x,1);
        }
        for(int i=0; i<n; i++)
            printf("%d\n",a[i]);
    }
    return 0;
}

发布了36 篇原创文章 · 获赞 10 · 访问量 1924

猜你喜欢

转载自blog.csdn.net/weixin_44003265/article/details/97288573