POJ2299 Ultra-QuickSort (归并排序求逆序数模板)




#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>

#define max(a,b) (a>b)?a:b
#define min(a,b) (a>b)?b:a
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
#define LL __int64
const int maxn = 500100;

using namespace std;
LL a[maxn],b[maxn],n,sum = 0;
/*void Sort(LL L,LL mid,LL R)
{
    LL s = L,e = mid + 1;
        LL num = 0;
        while(s<=mid&&e<=R)
        {
            if(a[s]<=a[e])
            {
                b[num++] = a[s++];
            }
            else
            {
                b[num++] = a[e++];
                sum += mid - s + 1;
            }
        }
        while(s<=mid)
        {
            b[num++] = a[s++];
        }
        while(e<=L)
        {
            b[num++] = a[e++];
        }
        for(int i = 0;i<num;i++)
            a[L+i] = b[i];
}*/
void gb_sort(LL *a,LL L,LL R)
{
    if(L<R)
    {
        LL mid = (L+R)/2;
        gb_sort(a,L,mid);
        gb_sort(a,mid+1,R);
       // Sort(L,mid,R);
        LL s = L,e = mid + 1;
        LL num = 0;
        while(s<=mid&&e<=R)
        {
            if(a[s]<=a[e])
            {
                b[num++] = a[s++];
            }
            else
            {
                b[num++] = a[e++];
                sum += mid - s + 1;
            }
        }
        while(s<=mid)
        {
            b[num++] = a[s++];
        }
        while(e<=L)
        {
            b[num++] = a[e++];
        }
        for(int i = 0;i<num;i++)
            a[L+i] = b[i];
    }
}
int main()
{
    while(scanf("%I64d",&n),n)
    {
        sum = 0;
        for(int i = 0;i<n;i++)
        {
            scanf("%I64d",&a[i]);
        }
        gb_sort(a,0,n-1);
        cout<<sum<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值