In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,
Ultra-QuickSort produces the output
0 1 4 5 9 .
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
思路:就是让你求逆序对,上次是用归并排序来写的,这次用的树状数组来写的,复杂度都是O(n),但个人认为还是树状数组略方便,用树状数组求逆序对就是每次都更新1,然后每次相加i-sum[i],就是前面有多少数比它大。
这题需要离散化处理一下数据,防止数据过大爆(好像有人没有离散化也可以过)。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 5e5 + 10;
int c[maxn], p[maxn];
int n;
struct node
{
int val, pos;
bool operator < (const node &r)
{
return val < r.val;
}
}a[maxn];
int lowbit(int i)
{
return i & -i;
}
void update(int i)
{
while(i <= n)
{
c[i]++;
i += lowbit(i);
}
}
int sum(int i)
{
int ans = 0;
while(i > 0)
{
ans += c[i];
i -= lowbit(i);
}
return ans;
}
int main()
{
while(~scanf("%d", &n) && n)
{
memset(c, 0, sizeof(c));
for(int i = 1; i <= n; ++i)
{
scanf("%d", &a[i].val);
a[i].pos = i;
}
sort(a + 1, a + n + 1);
for(int i = 1; i <= n; ++i)
{
p[a[i].pos] = i;
}
ll ans = 0;
for(int i = 1; i <= n; ++i)
{
update(p[i]);
ans += i - sum(p[i]);
}
printf("%lld\n", ans);
}
return 0;
}