为啥超时呢?

P1908 逆序对

二哈家的金毛 @ 2022-03-08 15:36:13

使用的是归并进行排序统计,为啥会超时,应该如何改进?求大佬指点呜呜呜

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

int b[5000001];
int a[5000001];
long long int ans=0;
inline void msort(int *a,int l,int r)
{
    int mid=(l+r)/2;
    if(l==r)
    return ;
    else 
    {
        msort(a,l,mid);
        msort(a,mid+1,r);
    }
    int t=l;
    int i=l;int j=mid+1;
    while(i<=mid&&j<=r)
    {
        if(a[i]>a[j])
        {
            b[t++]=a[j];
            ans+=(mid-i+1);
            j++;
        }
        else
        {
            b[t++]=a[i++];
        }
    }
    while(i<=mid)
    {
        b[t++]=a[i++];
    }
    while(j<=r)
    {
        b[t++]=a[j++];
     }
    for(int m=1;m<=r;m++)
    {
        a[m]=b[m];
     } 
     return ;
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    msort(a,1,n);
    cout<<ans;
    return 0;
}

by Jasper08 @ 2022-03-08 16:07:10

@二哈家的金毛

//P1908 逆序对

#include <cstdio>

using namespace std;

typedef long long ll;

const int N = 1e6 + 10;

int n;
int q[N], tmp[N];

ll msort(int l, int r) //归并模板 
{
    if (l >= r)
        return 0;

    int mid = l + r >> 1;
    ll res = msort(l, mid) + msort(mid+1, r);

    int k = 0, i = l, j = mid+1;
    while (i <= mid && j <= r)
    {
        if (q[i] <= q[j])
            tmp[k++] = q[i++];
        else
        {
            tmp[k++] = q[j++];
            res += mid - i + 1;
        }
    }
    while (i <= mid) 
        tmp[k++] = q[i++];
    while (j <= r)
        tmp[k++] = q[j++];

    for (int i = l, j = 0; i <= r; ++i, ++j)
        q[i] = tmp[j];

    return res;
}

int main() 
{
    scanf("%d", &n);
    for (int i = 0; i < n; ++i)
        scanf("%d", &q[i]);

    printf("%lld", msort(0, n-1));

    return 0;
}

|