35pts求助

P1908 逆序对

liuyuanpei @ 2023-04-04 22:43:20

# include <iostream>
# include <cmath>
# include <cstring>
# include <string>
# include <algorithm>
# include <stack>
# include <queue>
# include <set>
# include <map>
using namespace std;
long long ans=0; 
int n,m,c[1000005];
int a[1000005],b[1000005];
int lowbit (int x){
    return x&-x;
}
void add(int x){
    for(;x<=n;x+=lowbit(x))
        c[x]++;  
}
int sum(int x) {
    long long cnt=0; 
    for(;x>0;x-=lowbit(x)) 
        cnt+=c[x];
    return cnt; 
}
bool cmp(int x,int y)  {
    return b[x]>b[y];
}
int main(){
    cin >>n;
    for(int i=1;i<=n;i++){
        cin >>b[i];
        a[i]=i;
    }
    sort(a+1,a+n+1,cmp); 
    for(int i=1;i<=n;i++){
        add(a[i]);  
        ans+=sum(a[i]-1);  
    }
    cout <<ans<<endl;
    return 0;  
}

by 氷の妖怪Cirno @ 2023-05-29 00:28:15

排序时没考虑相等的情况该怎么办


|