树状数组之逆序数
2015-01-23 09:32
316 查看
其中操作的环节需要注意的是树状数组的本质是求小于的等于一个数的个数,所以求逆序数是需要进行相应的处理,以排序之后的下标减去该下标对应的元素进行的sum操作得到的结果就是逆序数。程序如下:
#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> using namespace std; const int N = 500005; struct Node { int val;//存储的是每个值,用以排序 int pos;//存储的是每个值出事序列的下标,保证在排序之后仍保留原本的顺序 }; Node node ; int c , reflect , n; bool cmp(const Node& a, const Node& b) { return a.val < b.val; } int lowbit(int x) { return x & (-x); } void update(int x) { while (x <= n) { c[x] += 1; x += lowbit(x); } } int getsum(int x) { int sum = 0; while (x > 0) { sum += c[x]; x -= lowbit(x); } return sum; } int main() { while (scanf("%d", &n) != EOF && n) { for (int i = 1; i <= n; ++i) { scanf("%d", &node[i].val); node[i].pos = i; } sort(node + 1, node + n + 1, cmp); //排序 for (int i = 1; i <= n; ++i) reflect[node[i].pos] = i; //离散化 for (int i = 1; i <= n; ++i) c[i] = 0; //初始化树状数组 long long ans = 0; for (int i = 1; i <= n; ++i) { update(reflect[i]); int b= i - getsum(reflect[i]); ans+=b; } printf("%lld\n", ans); } return 0; }
相关文章推荐
- 树状数组求逆序数
- 用树状数组求逆序对数(poj2299)
- BZOJ5058 期望逆序对 【矩乘 + 组合数学 + 树状数组】
- POJ 3067 Japan(树状数组:求逆序)
- Bzoj 2141: 排队 分块,逆序对,树状数组
- 【树状数组--求逆序数】poj3067 Japan
- 树状数组求逆序数
- bzoj4989 [Usaco2017 Feb]Why Did the Cow Cross the Road(树状数组求逆序对个数)
- 树状数组求逆序数
- hdu5147 Sequence II树状数组求逆序对
- PKU 2299 【逆序数+树状数组】
- 树状数组--求逆序对-离散化
- POJ2299Ultra-QuickSort(归并排序 + 树状数组求逆序对)
- HDU3465--Life is a Line(树状数组求逆序数,离散化)
- Ultra-QuickSort (poj 2299 归并排序 || 树状数组 求逆序对)
- hdu5792 多校5 World is Exploding【树状数组求逆序数】
- 树状数组求逆序对
- poj 3067(树状数组求逆序对)
- Codeforces645B【树状数组求逆序数】
- 树状数组求逆序对数