hdu stars 简单的树状数组

来源:互联网 发布:seo搜索好学吗 编辑:程序博客网 时间:2024/06/07 06:41

写在前面:

刚刚学树状数组,只是对几个基本操作还有树状数组的组建有了一点了解。这个题目也是看了解题报告之后才写出来的。

另外,大家做一下 http://125.221.232.253/JudgeOnline/problem.php?id=1481

Stars

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 30   Accepted Submission(s) : 19
Problem 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
51 15 17 13 35 5
 

Sample Output
12110
 

Source
Ural Collegiate Programming Contest 1999
 

Statistic | Submit | Back


题目大意:

让你求每一个星星的level值,而每一个星星的level数值等于,这个星星左下角的星星的个数。之后输出level值为0---n-1,每个level值有几个星星符合。


解题思路;

就是求每一个点的左下角的点有多少个,即为这个点的level值,然后输出level值为0---n-1的点分别有多少。

因为点的输入是按照坐标Y的升序输入,如果坐标y相同则按x的升序输入。所以我们在计算每个点的level数值,即求该点左下角的点有多少个的时候,就可以不用管y是多少,只求《=x的点有多少个就可以。假设输入 5 5,那么就把x为0---5的点统计起来,即为5 5这一点的level值。设一个数组存level的个数,每次求出一个level值,在该数组对应的下标的那个元素上都要++.假设我们设一个一维数组去存贮横坐标为0-----n的点的个数,那么每一次输入一个点的时候,坐标中相应的位置都会+1,当数组中的元素变动后再求值如果总是去遍历整个数组肯定会超时。比如,计算一次level,最坏的情况是m,一共计算n-1次,那么肯定超时了。所以在修改区间内一个元素,再求区间和的这个问题上,很符合树状数组的特点。所以,利用树状数组去做。。。。。


代码如下:



#include<stdio.h>#include<string.h>#define MAX 32010int c[MAX],a[MAX];int lowbit(int x){return x&(-x);}int sum(int end){int sum=0;while(end>0){sum+=c[end];end-=lowbit(end);}return sum;}void updata(int pos,int num){while(pos<=MAX){c[pos]+=num;pos+=lowbit(pos);}}int main(){int n;int i,j,k;int x,y;int cns;while(scanf("%d",&n)!=EOF){memset(a,0,sizeof(a));memset(c,0,sizeof(c));for(i=1;i<=n;i++){scanf("%d%d",&x,&y);cns=sum(x+1);a[cns]++;updata(x+1,1);}for(j=0;j<n;j++)printf("%d\n",a[j]);}return 0;}


原创粉丝点击