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
思路:
求逆序的个数就是求当前这个数左边有多少个数比他大;
用结构题记录输入的数的值和输入时的原始位置,按照数从大到小排序,每次插入一个当前最大的数,并把其所在的位置赋值1,再查询插入位置前有多少个数(求1到插入位置-1的和),这个数就是逆序数,(因为先插入则比这个大,但是又在这个数前面,所以之前插入的这个数逆序了)然后累加就行了;
由于数组大小可能为500000,而又要求区间和,所以要用树状数组;
代码;
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int n; int c[500010]; struct node { int val; int id; }a[500010]; int cmp(node x,node y) { return x.val>y.val; } int lowbit(int x) { return x&(-x);//求x的最低位的1,也是求x的管辖范围; } void update(int x,int y)//向上更新树形数组; { while(x<=n) { c[x]+=y; x+=lowbit(x); } } int getsum(int x)//向下求和; { int t=0; while(x>0) { t+=c[x]; x-=lowbit(x); } return t; } int main() { while(scanf("%d",&n)&&n) { memset(c,0,sizeof(c));//c数组要先清0; for(int i=1;i<=n;i++) { scanf("%d",&a[i].val); a[i].id=i; } sort(a+1,a+1+n,cmp);//从大到小排序; long long ans=0; for(int i=1;i<=n;i++) { update(a[i].id,1);//每次都插入当前最大的; ans+=getsum(a[i].id-1);//计算插入的数前面有多少个数已经插入了 } printf("%lld\n",ans); } return 0; }