UVa 10810 Ultra-QuickSort(逆序对)

题目描述:给出n个整数,求其逆序对个数。

数据范围:n<500,000, 整数<999,999,999

分析:使用归并排序求逆序对

/*
	PROG: UVa10810
*/

#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;

#define MAXN 500010
int a[MAXN], b[MAXN], c[MAXN];

#define DEBUG 1
#define LOG(...) do { if (DEBUG) fprintf(stderr, __VA_ARGS__); } while(0)
typedef long long LL;
LL Merge(int l, int r) {
	if (l >= r) return 0;
	int m = (l+r) >> 1;
	LL ret = Merge(l, m)+Merge(m+1,r);
	memcpy(b, a+l, sizeof(int)*(m+1-l));
	memcpy(c, a+m+1, sizeof(int)*(r-m));
	int i, j;
	i = j = 0;
	for (int k = l; k <= r; ++k) {
		if (i == m+1-l) a[k] = c[j++];
		else if (j == r-m) a[k] = b[i++], ret += r-m;
		else if (b[i] > c[j]) a[k] = c[j++];
		else a[k] = b[i++], ret += j;
	}
	return ret;
}

int main(void) {
	int n;
	while (scanf("%d", &n), n) {
		for (int i = 0; i < n; ++i)
			scanf("%d", a+i);
		printf("%lld\n", Merge(0, n-1));
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值