您的位置:首页 > 其它

树状数组之逆序数

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: