Description
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.
Ultra-QuickSort produces the output
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
题目大意:
求逆序对,方法多种多样,树状数组、线段树、归并都可以做,现在练的是树状数组,所以介绍一下树状数组的解释。
总共有N个数,如何判断第i+1个数到最后一个数之间有多少个数小于第i个数呢?不妨假设有一个区间 [1,N],只需要判断区间[i+1,N]之间有多少个数小于第i个数。如果我们把总区间初始化为0,然后把第i个数之前出现过的数都在相应的区间把它的值定为1,那么问题就转换成了[i+1,N]值的总和。再仔细想一下,区间[1,i]的值+区间[i+1,N]的值=区间[1,N]的值(i已经标记为1),所以区间[i+1,N]值的总和等于N-[1,i]的值!因为总共有N个数,不是比它小就是比它(大或等于)。
现在问题已经转化成了区间问题,枚举每个数,然后查询这个数前面的区间值的总和,i-[1,i]既为逆序数
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
#define N 500001
struct node{
int val,id;
};
node p[N];
int n,c[N],ha[N];
int cmp(node a,node b)
{
return a.val<b.val;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int val)
{
while (x<=n)
{
c[x]+=val;
x+=lowbit(x);
}
}
int sum(int x)
{
int ans=0;
while (x>=1)
{
ans+=c[x];
x-=lowbit(x);
}
return ans;
}
int main()
{
int i;
while (scanf("%d",&n),n)
{
for (i=1;i<=n;i++)
{
scanf("%d",&p[i].val);
p[i].id=i;
}
sort(p+1,p+n+1,cmp);
// for (i=1;i<=n;i++)
// printf("%d %d\n",p[i].id,p[i].val);
for (i=1;i<=n;i++)
ha[p[i].id]=i; //哈希数组里面代表的意义是第i个数字按顺序最终应放在ha[i]的位置上
memset(c,0,sizeof(c));
ll ans=0;
for (i=1;i<=n;i++)
{
update(ha[i],1);
ans+=(i-sum(ha[i])); //
}
printf("%lld\n",ans);
}
return 0;
}