返回题解分享
讨论 / 题解分享/ 帖子详情

求逆序对 - 题解

#include <bits/stdc++.h>
using ll = long long;
#define lowbit(x) (-x) & x
using namespace std;
const ll N = 2e5 + 9;
ll a[N], t[N];
ll n;
vector<ll> X;

void update(ll k, ll x) {
   for (int i = k; i <= n; i += lowbit(i)) {
       t[i] += x;
   }
}

ll bin(ll x) {
   return (lower_bound(X.begin(), X.end(), x) - X.begin() + 1);
}

ll getsum(ll k) {
   ll res = 0;
   for (int i = k; i; i -= lowbit(i)) {
       res += t[i];
   }
   return res;
}

signed main() {
   cin >> n;
   for (int i = 1; i <= n; ++i) {
       cin >> a[i];
       X.push_back(a[i]);
   }
   sort(X.begin(), X.end());
   X.erase(unique(X.begin(), X.end()), X.end());
   ll ans = 0;
   for (int i = 1; i <= n; i++) {
       ans += getsum(X.size()) - getsum(bin(a[i]));
       update(bin(a[i]), 1);
   }
   cout << ans << '\n';
   return 0;
}


#include<bits/stdc++.h>
#define int long long
#define INF 0x3f3f3f3f 
#define endl '\n'
using namespace std; 
const int N=1e6+9;

int n,a[N],temp[N];

inline int ms(int a[],int l,int r){
    if(l>=r) return 0;
    int mid=(l+r)>>1;
    int res=ms(a,l,mid)+ms(a,mid+1,r);
    int k=0,i=l,j=mid+1;
    while(i<=mid&&j<=r){
        if(a[i]<=a[j]) temp[k++]=a[i++];
        else{
            temp[k++]=a[j++];
            res+=mid-i+1;
        }
    }
    while(i<=mid) temp[k++]=a[i++];
    while(j<=r) temp[k++]=a[j++];
    for(int i=l,j=0;i<=r;i++,j++) a[i]=temp[j];
    return res;
}

inline void solve(){
    cin >> n;
    for(int i=0;i<n;++i) cin >> a[i];
    cout << ms(a,0,n-1) << endl;
}

signed main(){ 
   ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
   int _ = 1; 
   //int _; cin >> _;  
   while(_--) solve();
   return 0;
}
0 回复 0 转发 0 喜欢 4 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!