树状数组

 1 #include <iostream>
 2 using namespace std;
 3 int n;
 4 int d[10000];
 5 int lowbit(int x)
 6 {
 7     return x&(-x);
 8 }
 9 int query(int x)
10 {
11    int res=0;
12     while(x>0)
13     {
14         res+=d[x];
15         x-=lowbit(x);
16     }
17     return res;
18 }
19 void update(int x)
20 {
21     while(x<=n)
22     {
23         d[x]++;
24         x+=lowbit(x);
25     }
26 }
27 int main()
28 {
29     int x;
30 
31    cin>>n;
32    for(int i=0;i<n;i++)
33    {
34       d[i]=0;
35    }
36 
37 for(int i=0;i<n;i++)
38    {
39       cin>>x;
40       if(i==0)
41         {
42             cout<<query(x)<<' ';
43         }
44       else
45       {
46           cout<<query(x)<<' ';
47       }
48        update(x+1);
49    }
50    return 0;
51 }

 

posted @ 2022-02-07 16:29  九点的日落  阅读(20)  评论(0)    收藏  举报