TLE求助!用的是归并但复杂度还是n^2,

P1908 逆序对

_czx_ @ 2023-09-26 18:17:31

#include<iostream>
using namespace std;
int n;
int s[500050],a[500050];
long long ans;
void merge(int l,int r){
    if(l == r) return;
    int mid = (l+r)>>1;
    merge(l,mid);
    merge(mid+1,r);
    int i = l,j = mid+1,k = l;
    while(i<=mid&&j<=r){
        if(a[i]<=a[j]){
            s[k++] = a[i++];
        }else{
            ans+=mid-i+1;
            s[k++] = a[j++];
        }
    }
    while(i<=mid) s[k++] = a[i++];
    while(j<=r) s[k++] = a[j++];
    for(int i = 1;i<=r;i++){
        a[i] = s[i];
    }
}
int main(){
    ios::sync_with_stdio(false);cin.tie(0);
    cin >> n;
    for(int i = 1;i<=n;i++){
        cin >> a[i];
    }
    merge(1,n);
    cout << ans;
    return 0;
} 

by OldDriverTree @ 2023-09-26 18:30:07

merge 中的 for 应为 for(int i = l;i<=r;i++)


by _czx_ @ 2023-09-27 19:35:30

@OldDriverTree orz。


|