题目链接:http://poj.org/problem?id=2299
题意:求逆序对
先大赞一下markdown编辑器,今天知道了很多奥妙重重的功能。
听吉利说求逆序对还可以用树状数组?
于是激动的test了一发,吐槽一下,树状数组好像只能处理
ai
排列时候的情况,否则就需要按照他们的相对大小离散化(这么样第一次接触离散化,有点尴尬…)。注意,这道题需要开 long long(又被坑了….)。
代码:
// 树状数组离散化后求逆序对
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <map> // STL
#include <string>
#include <vector>
#include <queue>
#include <stack>
#define mpr make_pair
#define debug() puts("okkkkkkkk")
using namespace std;
typedef long long LL;
const int inf = 1 << 26;
struct nodes {
int val, pos;
} nds[1000005];
int n, a[1000005], c[1000005];
int cmp(nodes a, nodes b) {
return a.val > b.val;
}
#define lowbit(i) i&(-i)
void update(int x) {
for( int i = x; i <= n; i += lowbit(i) ) ++ c[i];
}
int query(int x) {
int ans = 0;
for ( int i = x; i; i -= lowbit(i)) ans += c[i];
return ans;
}
int main(){
while( scanf("%d", &n), n ) {
memset(c, 0, sizeof(c));
memset(nds, 0, sizeof(nds));
for ( int i = 1; i <= n; i ++ ){ scanf("%d", &nds[i].val); nds[i].pos = i; }
sort(nds+1, nds+n+1, cmp);
// 离散化
for ( int i = 1; i <= n; i ++ ) {
if(nds[i].val != nds[i-1].val || i == 1) a[nds[i].pos] = n-i+1;
else a[nds[i].pos] = a[nds[i-1].pos];
}
LL ans = 0;
for ( int i = 1; i <= n; i ++ ) {
update(a[i]);
ans += (LL)i-query(a[i]);
}
printf("%lld\n", ans);
}
return 0;
}
吐槽一下,代码比归并排序还长,不过细节比较少,适合我这样的人….