求助归并TLE了orz

P1908 逆序对

SOMO @ 2024-12-01 14:02:06

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

LL count1=0;
#define N 500010

void Merge(int arr[],int tmp[],int l,int r,int mid){

    for(int p=l;p<=r;p++){
        tmp[p]=arr[p];
    }
    int i,j;
    int k=l;

    for(i=l,j=mid+1;i<=mid && r>=j;k++){
        if(tmp[i]>tmp[j]){
            arr[k]=tmp[j++];
            count1+=mid - i + 1;
        }
        else if(tmp[j]>tmp[i])
            arr[k]=tmp[i++];
    }
    while(i<=mid){
        arr[k++]=tmp[i++];
    }
    while(j<=r){
        arr[k++]=tmp[j++];
    }
}

void MergeSort(int arr[],int tmp[],int l,int r){
    if(l<r){
        int mid=(l+r)/2;
        MergeSort(arr,tmp,l,mid);
        MergeSort(arr,tmp,mid+1,r);
        Merge(arr,tmp,l,r,mid);
    }
}

void Msort(int arr[],int n){
    int* tmp=(int*)malloc(N*sizeof(int));
    if(tmp!=NULL){
        MergeSort(arr,tmp,0,n-1);
        free(tmp);
    }
    else
        cout<<"wrong"<<endl;
}

//快读
inline int read()
{
    int w=1,ans=0;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')w=-1;ch=getchar();}
    while(isdigit(ch)){ans=ans*10+(ch-'0');ch=getchar();}
    return w*ans;
}

int main(){
//    int n;
//    cin>>n;
    int n=read();
    int numbers[N];
    for(int i=0;i<n;i++){
        cin>>numbers[i];
    }
    Msort(numbers,n);
    cout<<count1<<endl;
    return 0;
}

by luvsicpt @ 2024-12-28 20:01:33

@lly66666AC了


上一页 |