题目链接:https://www.acwing.com/problem/content/description/790/ 题目如下:
#include <iostream>
#include <vector>
using namespace std;
using LL=long long;
const int N=100010;
LL arr[N];
LL merge(LL arr[],int l,int r);
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++) cin>>arr[i];
cout<<merge(arr,0,n-1)<<endl;
return 0;
}
LL merge(LL arr[],int l,int r){
if(l>=r) return 0;
int mid=(l+r)>>1;
LL res=merge(arr,l,mid)+merge(arr,mid+1,r);
int i=l,j=mid+1;
vector<int> temp;
while(i<=mid&&j<=r){
if(arr[i]<=arr[j]) temp.push_back(arr[i++]);
else {
temp.push_back(arr[j++]);
res+=mid-i+1;
}
}
while(i<=mid) temp.push_back(arr[i++]);
while(j<=r) temp.push_back(arr[j++]);
i=l;
for(auto e:temp) arr[i++]=e;
return res;
}
|