码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 2299 Ultra-QuickSort

时间:2015-01-24 15:51:02      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

 

/*
*POJ 2299 Ultra-QuickSort
*求逆序数
*树状数组
*离散化
*/

#include <cstdio>
#include <algorithm>
using namespace std;

#define lowbit(x) x&(-x)
#define int long long
int n;
const int MAXN = 500010;

struct Node {
	int data;
	int pos;
} nodes[MAXN];

bool cmp(Node a, Node b)
{
	return a.data < b.data;
}
int c[MAXN];
int sorted[MAXN];
void update(int x)
{
	for (int i = x; i <= n; i += lowbit(i)) {
		c[i] ++;
	}
}

int getSum (int x)
{
	int sum = 0;
	for (int i = x; i > 0; i -= lowbit(i)) {
		sum += c[i];
	}
	return sum;
}

main()
{

	while (~scanf("%d", &n) && n) {
		for (int i = 0; i <= n; i++) {
			c[i] = 0;
		}

		for (int i = 1; i <= n; i++) { /*离散化*/
			scanf("%d", &nodes[i].data);
			nodes[i].pos = i;
		}
		sort(nodes, nodes + n + 1, cmp);
		for (int i = 1; i <= n; i++) {
			sorted[nodes[i].pos] = i;
		}
		int ans = 0;
		for (int i = 1; i <= n; i++) {
			update(sorted[i]);
			ans += (i - getSum(sorted[i]));
		}
		printf("%lld\n", ans);
	}
}

  

POJ 2299 Ultra-QuickSort

标签:

原文地址:http://www.cnblogs.com/subrshk/p/4245971.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!