35分求助

P1908 逆序对

Gohldg @ 2023-08-07 09:11:32

死因做法:树状数组

代码:

#include <iostream>
#include <algorithm>
using namespace std;
#define int long long
int a[500001];
int b[500001];
int c[500001];
int n,m,x,y,ans;
int lowbit(int x){
    return (x&(-x));
}
int sum(int x){
    int num=0;
    for(int i=x;i>=1;i=i-lowbit(i)){
        num+=c[i];
    }
    return num;
}
bool cmp(int x,int y){
    return b[x]>b[y];
}
//int ask(int x,int y){
//  return sum(y)-sum(x-1);
//}
void add(int x,int y){
    for(int i=x;i<=n;i=i+lowbit(i)){
        c[i]+=y;
    }
}
signed main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>b[i];
        a[i]=i;
    }
    sort(a+1,a+1+n,cmp);
    for(int i=1;i<=n;i++){
        add(a[i],1);
        ans+=sum(a[i]-1);
    }
    cout <<ans;
    return 0;
}

by Root808 @ 2023-08-07 10:20:57

建议使用结构体,而不是a,b两个数组,排序的时候会出现问题


by Gohldg @ 2023-08-07 14:32:14

@Root808 会出现什么问题


by _Coffice_ @ 2023-08-08 10:54:47

二路归并算法了解一下


by wltorz @ 2023-08-08 16:25:39

@Gohldg 并且排序时要考虑相等情况


|