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
线段树离线更新,即等到查询第k大的值的所构成的逆序数时,即把前k-1个数更新,再进行查询即可,注意有重复元素的情况,此时只更新重复元素的最后一个元素就行了。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
struct number{
int num;
int pos;
}a[500005];
struct point{
int l,r;
int count;
}b[4000005];
int x,y,s;
long long sum;
bool cmp(const number &a,const number &b){
return a.num < b.num;
}
void buildTree(int o,int l,int r){
if(l == r){
b[o].l = b[o].r = l;
b[o].count = 0;
}
else{
int mid = (l + r) >> 1;
buildTree(o << 1,l,mid);
buildTree((o << 1)|1,mid + 1,r);
b[o].l = l,b[o].r = r,b[o].count = 0;
}
}
void updateTree(int o){
if(b[o].l == b[o].r){
b[o].count += s;
}
else{
int mid = (b[o].l + b[o].r) >> 1;
if(mid >= x){
updateTree(o << 1);
}
else{
updateTree((o << 1) | 1);
}
b[o].count += s;
}
}
void queryTree(int o){
if(b[o].l >= x && b[o].r <= y){
sum = sum + b[o].count;
}
else{
int lo = o << 1,ro = (o << 1) | 1;
if(b[lo].l <= y && b[lo].r >= x){
queryTree(lo);
}
if(b[ro].l <= y && b[ro].r >= x){
queryTree(ro);
}
}
}
int main(){
int n;
while(cin >> n && n){
for(int i = 0;i < n;++i){
scanf("%d",&a[i].num);
a[i].pos = i;
}
sort(a,a + n,cmp);
sum = 0,s = 1;
buildTree(1,0,n - 1);
for(int i = 0;i < n;++i){
//cout << a[i].pos << " " << a[i].num << endl;
x = a[i].pos + 1,y = n - 1;
queryTree(1);
x = a[i].pos;
if(a[i].num != a[i + 1].num && i != n - 1){
updateTree(1);
s = 1;
}
else{
s++;
}
}
cout << sum << endl;
}
return 0;
}