码迷,mamicode.com
首页 > 编程语言 > 详细

树状数组求逆序对个数

时间:2021-04-10 13:40:10      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:end   +=   cst   pac   printf   ini   main   line   ++   

#include<cstdio>
#include<algorithm>
const int N = 1e6 + 1;
int n, t[N];
namespace lsh{
	int lsh[N], tmp[N];
	void init() {
		for (int i = 1; i <= n; ++i)
			tmp[i] = lsh[i];
		std::sort(tmp + 1, tmp + n + 1);
		auto end = std::unique(tmp + 1, tmp + n + 1);
		for (int i = 1; i <= n; ++i) 
			lsh[i] = std::lower_bound(tmp + 1, end, lsh[i]) - tmp;
	}
}
inline int lowbit(int x) { return x & -x; }
void add(int p) { for (; p <= n; p += lowbit(p))++t[p]; }
int sum(int p) { int s = 0; for (; p; p -= lowbit(p))s += t[p]; return s; }
int main() {
	scanf("%d", &n);
	for (int i = 1; i <= n; ++i) 
		scanf("%d", lsh::lsh+i);
	lsh::init();
	int ans = 0;
	for (int i = 1; i <= n; ++i) {
		add(lsh::lsh[i]);
		ans += i - sum(lsh::lsh[i]);
	}
	printf("%d\n", ans);
}

树状数组求逆序对个数

标签:end   +=   cst   pac   printf   ini   main   line   ++   

原文地址:https://www.cnblogs.com/dwt2021/p/14640152.html

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