cjweffort

博客园 首页 联系 订阅 管理


/*树状数组求解逆序对
(1)对数据进行离散化
(2)构建树状数组求解逆序对*/
// poj2299逆序对_树状数组.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"#include <stdio.h>#include <algorithm>using namespace std;const int N = 500003;typedef struct Node{int value;int no;int tag;}Node;Node node[N], oriNode[N];int n;int sub[N];bool cmp1(Node m1, Node m2){return m1.value < m2.value;}bool cmp2(Node m1, Node m2){return m1.tag < m2.tag;}void serialize(){sort(node + 1, node + n + 1, cmp1);int cnt = 1;node[1].no = 1;for(int i = 2; i <= n; i++){if(node[i].value != node[i - 1].value)node[i].no = ++cnt;elsenode[i].no = node[i - 1].no;}sort(node + 1, node + n + 1, cmp2);}int lowbit(int x){return x & (-x);}void update(int pos, int inc){while(pos <= n){sub[pos] += inc;pos += lowbit(pos);}}int sum(int pos){int ret = 0;while(pos > 0){ret += sub[pos];pos -= lowbit(pos);}return ret;}int main(){while(~scanf("%d", &n) && n){memset(sub, 0, sizeof(sub));for(int i = 1; i <= n; i++){scanf("%d", &node[i].value);node[i].tag = i;}serialize();long long ans = 0;for(int i = 1; i <= n; i++){update(node[i].no, 1);ans += i - sum(node[i].no);}printf("%lld\n", ans);}return 0;}


posted on 2013-10-14 21:11  cjweffort  阅读(127)  评论(0编辑  收藏  举报