30分求助

P1908 逆序对

_wakeup @ 2024-05-19 10:01:21

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<cstdlib>
#include<queue>
#include<vector>
#define ll long long
#define INF 2147483647
using namespace std;
int n,a[400100],t[400100],ans;
void merge_sort(int l,int r)
{
    int mid=(l+r)/2;
    if(l==r)return;
    merge_sort(l,mid);
    merge_sort(mid+1,r);
    for(int i=l,j=l,k=mid+1;i<=r;i++)
    {
        if(j==mid+1)t[i]=a[k++];
        else if(k==r+1)t[i]=a[j++];
        else if(a[j]<a[k])t[i]=a[j++];
        else t[i]=a[k++],ans+=mid-j+1;;
    }
    for(int i=l;i<=r;i++)a[i]=t[i];
}
int main()
{
    cin>>n;
    for(int i=n;i>=1;i--)cin>>a[i];
    merge_sort(1,n);
    cout<<ans<<endl;
    return 0;
}

by GLY0912 @ 2024-05-19 14:31:18

要用树状数组


|