归并排序50分求助

P1908 逆序对

计算机陈斌 @ 2020-04-24 14:34:50

  cpp
  #include <bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 10;
int a[maxn], tmp[maxn];
long long ans = 0;
void mergeSort(int a[], int l, int r) {
    if (l >= r) {
        return;
    }
    int mid = (l + r) / 2;

    mergeSort(a, l, mid);
    mergeSort(a, mid + 1, r);

    int k1 = l, k2 = mid + 1, k3 = l;
    while (k1 <= mid && k2 <= r) {
        if (a[k1] <= a[k2]) 
            tmp[k3++] = a[k1++];
        else 
            tmp[k3++] = a[k2++], ans += (mid - k1 + 1);
    }
    while (k1 <= mid) tmp[k3++] = a[k1++];
    while (k2 <= r) tmp[k3++] = a[k2++];

    // tmp[l, r] => a[l, r]
    for (int i = l; i <= r; ++i) a[i] = tmp[i];
}

inline int read(){//快读
    char ch=getchar();
    int x=0,f=1;
    while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=getchar();
    return x*f;
}
int main() {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) a[i] = read();
    mergeSort(a, 1, n);

    printf("%d", ans);
    return 0;
}

by liqingyang @ 2020-04-24 14:36:22

@计算机陈斌 long long


by liqingyang @ 2020-04-24 14:36:37

@计算机陈斌 printf("%d", ans);---->printf("%lld", ans);


by 计算机陈斌 @ 2020-04-24 14:38:07

@liqingyang 奥,没看到


by 计算机陈斌 @ 2020-04-24 14:40:47

@liqingyang 大佬能不能给个联系方式


by liqingyang @ 2020-04-24 14:41:51

@计算机陈斌 我没有什么联系方式,因为我是xxs,如果您愿意的话,可以直接洛谷私信


by Kubic @ 2020-04-24 14:42:18

武陵人石锤


by 计算机陈斌 @ 2020-04-24 14:43:24

@liqingyang 好的


by 二叉苹果树 @ 2020-04-24 14:55:42

归并排序写这么长


|