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
题意:给你一个长度为n的序列,问你这个序列的逆序数是多少
思路:考虑例子上的一个序列:9 1 0 5 4,每次我们取该序列中最小的数,计算出这个数的逆序数,然后将这个数删掉。
第一次,我们取0,0对答案贡献2,序列变为9 1 5 4;
第二次,我们取1,1对答案贡献1,序列变为9 5 4;
第三次,我们取4,4对答案贡献2,序列变为9 5;
第四次,我们取5,5对答案贡献1,序列变为9;
第四次,我们取9,9对答案贡献0,序列为空,结束;
我们可以用线段树实现
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=5e5+100;
typedef long long ll;
ll sum[maxn*4],ans;
struct node{
ll val;
int id;
}a[maxn];
int n;
void pushup(int cur)
{
sum[cur]=sum[cur<<1]+sum[cur<<1|1];
}
void build(int l,int r,int cur)
{
if(l==r)
{
sum[cur]=0;
return ;
}
int m=(l+r)>>1;
build(l,m,cur<<1);
build(m+1,r,cur<<1|1);
pushup(cur);
}
void update(int tar,ll val,int l,int r,int cur)
{
if(l==r)
{
sum[cur]=val;
return ;
}
int m=(l+r)>>1;
if(tar<=m) update(tar,val,l,m,cur<<1);
else update(tar,val,m+1,r,cur<<1|1);
pushup(cur);
return ;
}
ll query(int L,int R,int l,int r,int cur)
{
if(L<=l&&r<=R) return sum[cur];
ll ans=0;
int m=(l+r)>>1;
if(L<=m) ans+=query(L,R,l,m,cur<<1);
if(R>m) ans+=query(L,R,m+1,r,cur<<1|1);
return ans;
}
bool cmp(node x,node y)
{
return x.val<y.val;
}
int main()
{
while(~scanf("%d",&n)&&n)
{
ans=0;
build(1,n,1);
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i].val);
a[i].id=i;
update(i,1,1,n,1);
}
sort(a+1,a+1+n,cmp);
for(int i=1;i<=n;i++)
{
update(a[i].id,0,1,n,1);
ans+=query(1,a[i].id,1,n,1);
}
printf("%lld\n",ans);
}
return 0;
}