1. 程式人生 > >樹狀數組的進階運用(Stars 數星星)

樹狀數組的進階運用(Stars 數星星)

p s 計算 right star http 復雜 一個 examine maps

英文原題

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 5 1 1 5 1 7 1 3 3 5 5 Sample Output 1 2 1 1 0 翻譯題意

天文學家把天上的每顆星星都畫在一個平面上,並給定每顆的坐標。同時把星星左下方(包括橫坐標或者縱坐標一樣的)的星星數目定義為該星星的等級。天文學家想知道星星等級的分布。
例如上圖中,5號星星的等級為3(左下方的星星為1,2,4),2號與4號星星等級為1。上圖中等級為0的星星有1顆,等級為1的星星有2顆,等級為2的星星有1顆,等級為3的星星有1顆。
請寫一個程序計算屏幕上每一個等級的星星數。

仔細審題之後,發現是樹狀數組,因為輸入的xy的值是有序的,所以只需要建立c[x]表示橫坐標小於等於x的符合要求的點有幾個,運用到樹狀數組的基礎知識,統計出即可。

下面給出代碼

 1 //樹狀數組基本框架的搭建(維護和查詢都是O(lgn)的復雜度) 
 2 #include<iostream>
 3 #include<cstdio>
 4 #include<cstdlib>
 5 #include<cstring>
 6 #include<string>
 7 using namespace std;
 8 int n,a,b;
 9 int c[40000],ans[40000];//註意數組的大小
10 
11 int lowbit(int k)
12 {
13      return k&(-k);
14      
15 }
16 int add(int k,int num)
17 {
18     while(k<=32010)//此處的32010應為n的最大值+2
19     {
20          c[k]+=num;
21          k+=lowbit(k);
22     }
23 }
24 int sum(int k)
25 {
26     int Sum=0;
27     while(k>0)
28     {
29         Sum+=c[k];
30         k-=lowbit(k);
31     }
32     return Sum;
33 }
34 
35 
36 int main()
37 {
38      cin>>n;
39      for(int i=1;i<=n;i++)
40      {
41         cin>>a>>b;
42         a=a+1;//樹狀數組的下標需要從1開始,而數據從0開始,故此+1;
43         ans[sum(a)]++;
44         add(a,1); 
45      }
46      for(int i=0;i<n;i++)
47        cout<<ans[i]<<endl;
48     return 0;
49 }

樹狀數組的進階運用(Stars 數星星)