您的位置:首页 > 产品设计 > UI/UE

POJ-2299 Ultra-QuickSort 逆序对统计

2018-02-04 21:01 363 查看
基本的树状数组求逆序对

// Ultra-QuickSort
// http://poj.org/problem?id=2299 
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#define forloop(i, a, b) for(int i = a; i < b; i++)
#define fordown(i, a, b) for(int i = a; i > b; i--)

using namespace std;

const int maxn = 500010;
typedef long long LL;

struct Node {
int val, id;
};

int n;
Node a[maxn];
int arr[maxn];

inline int lowbit(int x) {
return x & -x;
}

void add(int x, int v) {
for (int i = x; i < n + 4; i += lowbit(i)) {
arr[i] += v;
}
}

LL sum(int x) {
LL s = 0;
for (int i = x; i ; i -= lowbit(i)) {
s += arr[i];
}
return s;
}

struct NodeCmp {
bool operator() (const Node& l, const Node& r) {
return l.val < r.val;
}
};

int main() {
while (cin >> n) {
if (n == 0) break;
memset(arr, 0, sizeof(int) * (n + 10));
forloop(i, 1, n+1) {
scanf("%d", &a[i].val);
a[i].id = i;
}
sort(a+1, a+1+n, NodeCmp());
LL ans = 0;
fordown(i, n, 0) {
ans += sum(a[i].id - 1);
add(a[i].id, 1);
}
cout << ans << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  树状数组