树状数组hd1541

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 int t, x, y, a[32010], b[32010];
 5 #define  N 32010
 6 int lowbit(int x)
 7 {
 8     return x&(-x);//返回x所在节点,很巧妙  eg:d[1]=a1;d[2]=a1+a2;d[3]=a3;d[4]=a1+a2+a3+a4;
 9 }
10 void add(int x, int y)//所有包含a[x]的区间都加a[x]
11 {
12     while(x<N)
13     {
14         b[x]+=y;
15         x+=lowbit(x);//返回x所在节点的父节点
16     }
17 }
18 int getsum(int x)//计算前x个数组的值
19 {
20     int sum=0;
21     while(x>0)
22     {
23         sum+=b[x];
24         x-=lowbit(x);//返回x所在节点的子节点
25     }
26     return sum;
27 }
28 int main()
29 {
30     while(cin>>t)
31     {
32         memset(a,0,sizeof(a));
33         memset(b, 0, sizeof(b));
34         for(int i=0; i<t; i++)
35         {
36             cin>>x>>y;
37             x+=1;
38             a[getsum(x)]++;
39             add(x,1);
40         }
41         for(int i=0; i<t; i++)
42             cout<<a[i]<<endl;
43     }
44     return 0;
45 }

//http://acm.hdu.edu.cn/showproblem.php?pid=1541

posted @ 2015-10-25 19:28  海无泪  阅读(130)  评论(0编辑  收藏  举报