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.
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
题意
对一行数进行排序,方法是交换相邻两个数,问需要交换多少次,可以排成升序。
思路
对于5 4 3 2 1而言,交换的次数是0+1+2+3+4=10,每次加上前面大于该位的个数,5的前面没有比5大的,4的前面有一个比4大的(5),3的前面有2个比3大的(5和4)。每次加入一个数,然后计算比他大的个数。
用树状数组维护等于n的有多少个数。 每次先增加一个数的时候,计算前面增加的数有多少个比他大,则答案增加这个个数。
sum(x)是小于等于x的个数,i是当前所有数量,i - sum(x)就是大于x 的个数。
最大9 9999 9999,太大无法建立数组,但是实际只有50 0000个数,可以将其离散化,比如1,100,3,80,2;可以离散化为1,5,3,4,2。
ans用long long 保存,可能会超int。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 500010;
int c[maxn],tt[maxn];
int n;
ll ans;
struct node
{
int x,id;
}a[maxn];
bool cmp(node a,node b)
{
return a.x<b.x;
}
int lowbit(int x)
{
return x & -x;
}
int sum(int x)
{
int res=0;
while(x>0)
{
res += c[x];
x -= lowbit(x);
}
return res;
}
void update(int x)
{
while (x<=n)
{
c[x]++;
x += lowbit(x);
}
}
int main()
{
while(~scanf("%d",&n))
{
if(n==0) break;
ans = 0;
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++){
scanf("%d",&a[i].x);
a[i].id = i;
}
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;i++) tt[a[i].id] = i;
for(int i=1;i<=n;i++){
update(tt[i]);
ans += i-sum(tt[i]);
}
printf("%lld\n",ans);
}
}