洛谷P1908 逆序对 (树状数组+离散化)

模板题,树状数组加上离散化求逆序对。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long LL;
 4 const int N=5e5+10;
 5 int n,a[N],b[N],c[N];
 6 LL ans;
 7 
 8 int lowbit(int x){
 9     return x&(-x);
10 }
11 
12 void ins(int x){
13     while(x<=n){
14         c[x]++;
15         x+=lowbit(x);
16     }
17 }
18 
19 LL que(int x){
20     LL sum=0;
21     while(x){
22         sum+=c[x];
23         x-=lowbit(x);
24     }
25     return sum;
26 }
27 
28 int main(){
29     scanf("%d",&n);
30     for(int i=1;i<=n;i++){
31         scanf("%d",&a[i]);
32         b[i]=a[i];
33     }
34     sort(b+1,b+n+1);
35     int cnt=unique(b+1,b+n+1)-b-1;
36     for(int i=1;i<=n;i++){
37         int x=lower_bound(b+1,b+cnt+1,a[i])-b;
38         ins(x);
39         ans+=i-que(x);
40     }
41     cout<<ans;
42 }

 

posted @ 2022-04-22 15:54  YHXo  阅读(41)  评论(0)    收藏  举报