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
题意:计算逆序数
树状数组离散化。点的范围太大,不可能开一个大数组,然后利用前缀和统计小于等于该位置的数有几个,注意到最多只有500000个数,所以使用离散化这一思想,缩小点的范围,但是维持其相对大小关系不变。
具体做法,类似于映射,每个数值对应一个数字,这里可以直接用输入的下标。
结构体内容:值和下标(下标就是离散化后的值)
样例输入: 9 1 0 5 4
结构体index:1 2 3 4 5
目标:保持原来的相对大小关系,所以目标就是将9 1 0 5 4映射成5 2 1 4 3
排序之后:0 1 4 5 9
下标:3 2 5 4 1
利用这步: for (int i = 1; i <= n; i++)
tmp[A[i].index] = i; //tmp[i]表示原来的第i个位置的元素是第i大
保证了其相对大小关系不变
对应到9 1 0 5 4就是第一个位置排第5,第二个位置排第2,第三个位置排第1....
tmp数组的下标:1 2 3 4 5
内容:5 2 1 4 3
然后就可以利用前缀和计算逆序数了
#include<iostream>
#include<cstdio>
#include<string.h>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
#define lowbit(x) x&(-x)
#define CLR(x) memset(x,0,sizeof(x))
const int maxn = 500000 + 50;
int n,t;
int sum[maxn];//sum[i]表示小于等于i的个数
int tmp[maxn];//离散化之后的数据
struct node{
int val, index;
node(int v = 0, int i = 0):val(v),index(i){}
bool operator < (const struct node& p)const{return val < p.val;}
}A[maxn];
void update(int x)
{
for (;x<=n;x+=lowbit(x))
sum[x]++;
}
int getsum(int x)
{
int ans = 0;
for (;x;x-=lowbit(x))
ans += sum[x];
return ans;
}
int main()
{
while (scanf("%d",&n)&&n)
{
CLR(sum); CLR(tmp);
for (int i = 1; i <= n; i++)
{
scanf("%d", &A[i].val);
A[i].index = i;//离散化
}
sort(A+1,A+n+1);
//离散化,原来的相对大小关系不变
//tmp数组保留了原来的大小关系
for (int i = 1; i <= n; i++)
tmp[A[i].index] = i;
long long cnt = 0L;
for (int i = 1; i <= n; i++)
{
update(tmp[i]);
cnt += i - getsum(tmp[i]);//计算逆序数
}
printf("%lld\n",cnt);
}
return 0;
}