Greater than its number and is less than its number (Fenwick tree)

 1 #include <bits/stdc++.h>
 2 #define ll long long
 3 using namespace std;
 4 int n,m;
 5 const int N=100005;
 6 ll cnt[N],arr[N],brr[N];
 7 vector<ll> vec;
 8 int getid(ll x) { return lower_bound(vec.begin(),vec.end(),x)-vec.begin()+1; }
 9 int lowbits(int x) { return x&-x; }
10 void add(int x,int value){ while(x<=N) cnt[x]+=value,x+=lowbits(x); }
11 int query(int x){
12     int sum=0;
13     while(x>0){ sum+=cnt[x],x-=lowbits(x); }
14     return sum;
15 }
16 int main(){
17     scanf("%d",&n);
18     for(int i=1;i<=n;i++) scanf("%lld",&ARR [I]), vec.push_back (ARR [I]);
 . 19      Sort (vec.begin (), vec.end ()); vec.erase (UNIQUE (vec.begin (), vec.end ()) , vec.end ());
 20 is      LL SUM = 0 ;
 21 is      for ( int I = . 1 ; <= n-I; I ++ ) {
 22 is          the Add (getId (ARR [I]), . 1 );
 23 is          BRR [I] + Query-I = (getId (ARR [I]));   // I- or less in front of it is greater than the number of its number 
24      }
 25  //     Memset (BRR, 0, the sizeof (BRR)); 
26 is      Memset (CNT, 0 , the sizeof (CNT));
 27      for ( int I = n-; I> =1;i--){
28         add(getid(arr[i]),1);
29         brr[i]+=query(getid(arr[i])-1);   //后面小于它的个数
30 //        cout << brr[i] << endl;
31     }
32     for(int i=1;i<=n;i++){
33         sum+=1LL*(1+brr[i])*brr[i]/2;
34     }
35     cout << sum << endl;
36     return 0;
37 }
View Code

 

Guess you like

Origin www.cnblogs.com/qq-1585047819/p/11420383.html