今天发一个洛谷P1908逆序对的题解(归并排序)

#include 
using namespace std;
int a[500005];
int r[500005];
long long cnt ;//cnt=0;
void sort(int s,int t)
{
    if (s == t)
        return ;
    else
    {
        int mid = (s + t) / 2;
        sort(s,mid);
        sort(mid + 1,t);
        int i = s,j = mid + 1,x = s;
        while (i <= mid && j <= t)
        {
            if (a[i] <= a[j])
            {
                r[x] = a[i];
                x ++;
                i ++;
            }
            else
            {
                r[x] = a[j];
                x ++;
                j ++;
                cnt+=  mid - i + 1;
            }
        }
        while (i <= mid)
        {
            r[x] = a[i];
            x ++;
            i ++;
        }
        while (j <= t)
        {
            r[x] = a[j];
            x ++;
            j ++;
        }
        for (int i = s;i <= t;i ++)
            a[i] = r[i];
    }
}
int main()
{
    int n;
    cin >> n;
    for (int i = 1;i <= n;i ++)
    {
        cin >> a[i];
    }
    sort(1,n);//这里sort函数; 
    printf("%ld",cnt);
    return 0;
}

你可能感兴趣的:(算法,数据结构,c++)