http://poj.org/problem?id=2299
求逆序对最简单的绝对不会是树状数组,一定是归并排序(认真),不过树状数组会不会快一点呢?理论上应该是树状数组快一点(假如不进行离散化)。
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<map>
#include<set>
#include<stack>
#include<string>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
const int MAXN = 500000;
int a[MAXN + 5];
int tmp[MAXN + 5];
//分治,对[l,r]闭区间进行归并排序并统计逆序数
ll merge(int l, int r) {
if(l == r)
return 0;
int m = (l + r) >> 1;
ll res = 0;
res += merge(l, m);
res += merge(m + 1, r);
int i = l, j = m + 1, k = 0;
while(i <= m || j <= r) {
if(i > m) {
tmp[++k] = a[j++];
} else if(j > r) {
tmp[++k] = a[i++];
} else {
if(a[i] <= a[j]) {
tmp[++k] = a[i++];
} else {
res += m + 1 - i;
tmp[++k] = a[j++];
}
}
}
k = 0;
for(int i = l; i <= r; ++i) {
a[i] = tmp[++k];
}
return res;
}
int main() {
#ifdef Yinku
freopen("Yinku.in", "r", stdin);
#endif // Yinku
int n;
while(~scanf("%d", &n)) {
if(n == 0)
break;
for(int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
printf("%lld\n", merge(1, n));
}
}
带离散化的树状数组果然常数大得不行。
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<map>
#include<set>
#include<stack>
#include<string>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
const int MAXN = 500000;
int a[MAXN + 5];
int x[MAXN + 5];
int bit[MAXN + 5];
int n;
void add(int x) {
for(; x <= n; x += (x & -x))
++bit[x];
}
ll sum(int x) {
ll res = 0;
for(; x; x -= (x & -x))
res += bit[x];
return res;
}
int main() {
#ifdef Yinku
freopen("Yinku.in", "r", stdin);
#endif // Yinku
while(~scanf("%d", &n)) {
if(n == 0)
break;
memset(bit, 0, sizeof(bit[0]) * (n + 1));
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
x[i] = a[i];
}
sort(x + 1, x + 1 + n);
int xt = unique(x + 1, x + 1 + n) - (x + 1);
ll res = 0;
for(int i = 1; i <= n; ++i) {
a[i] = lower_bound(x + 1, x + 1 + xt, a[i]) - x;
add(a[i]);
res += i - sum(a[i]);
}
printf("%lld\n", res);
}
}
原文地址:https://www.cnblogs.com/Inko/p/11729741.html
时间: 2024-10-13 05:13:36