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.
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Input
The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.
Output
For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.
Sample Input
5
9 1 0 5 4
3
1 2 3
0
Sample Output
6
0 给你一个排序,让你求出这个排序中的逆序数.算是自己写的树状数组的第一道题吧,这个题首先用到离散化思想.
因为每个数都是小于1e9,而n的范围不超过5e5,而且我们只关心这些数的大小关系,所以我们就把这些数全部映射到1~n,然后再按照排好序的位置插进去就行了
这样子是不会影响最后算逆序数的.映射后的序列为reflect
接下来求逆序数,这时要用到树状数组,树状数组的功能是用来求数组前缀和的,我们假想有一个长度为n的数组,它现在每一位初始化为0
我们按照位置顺序将reflect中的每一个数插入到树状数组中,假设我们现在插入的数是第i个数,它的值为x
那么我就把刚刚假想的数组的第x位置变为1,即代表x被插入到该序列
那么每一次对于ans怎样+呢?
我们可以定义sum(x) x及小于x的数中有多少个元素已经被插入
这样的话sum(x)就是我们刚刚那个假想数组的前缀和了,我们用树状数组可以求
对于插入的第i个数,我们的ans+=i-sum(x),因为x是第i个数插进来的,之前插进来小于等于x的数为sum(x)
两者做差就是在x之前插入,而且值要大于x的数字的个数
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn =;
int reflect[maxn];
int c[maxn];
int n;
int lowbit (int x)
{
return x&(-x);
}
struct Node
{
int val,pos;
};
Node node[maxn];
bool cmp (Node q1,Node q2)
{
return q1.val<q2.val;
} void update (int x)
{
while (x<=n){
c[x]+=;//将我们想象的数组x位置附为1,直接就加到c[x]上了
x+=lowbit(x);//找父节点
}
}
int getsum (int x)
{
int sum=;
while (x>){
sum+=c[x];
/*求和时可以看作将x用二进制表示
temp=x;
每次加上c[temp],再把temp最后1位置上的值改成0
最后变成0时就求完了
如:求 101001
temp=101001 -> sum+=c[101001]
-> temp=101000 -> sum+=c[101000]
-> temp=100000 -> sum+=c[100000]
-> temp=000000 求完了
*/
x-=lowbit(x);
}
return sum;
}
int main()
{
//freopen("de.txt","r",stdin);
while (scanf("%d",&n)&&n){
for (int i=;i<=n;++i){
scanf("%d",&node[i].val);
node[i].pos=i;
}
sort(node+,node + n + , cmp);
for (int i=;i<=n;++i) reflect[node[i].pos]=i;//离散化映射到1~n
for (int i=;i<=n;++i) c[i]=;//初始化树状数组
long long ans=;
for (int i=;i<=n;++i){
update(reflect[i]);//插入一个数,更新一下
ans+=i-getsum(reflect[i]);//ans加一下
}
printf("%lld\n",ans);
}
return ;
}