传送门
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
首先对于逆序数可以通过遍历数组,把每个数字放到有序时对应的位置,放过就置为1,如果前面没有数字,那么他的逆序为i-getsum(i)
因为如果他的前缀和为0说明他前面没有数字放过,那么说明数组中在他前面的数字都放在他后面。
比如9 1 0 5 4,
先放9,得到0 0 0 0 1,此时ans+=1-getsum(1)=1-1=0;
再放1,得到0 1 0 0 1,此时ans+=2-getsum(2)=2-1=1;
接着放0,得到1 1 0 0 1,ans+=3-getsum(3)=3;
放5,得到1 1 0 1 1,ans+=4-getsum(4)=4;
最后放4,得到1 1 1 1 1,ans+=5-getsum(5)=6;
然后因为数据范围太大,不可能开那么大的数组,故需要离散化一下
AC代码如下
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdlib.h>
#define int long long
typedef long long ll;
using namespace std;
const int MANX=5e5+10;
int n,a[MANX],c[MANX];
struct node {
int val,index;
bool operator < (node const &rush) const {
return val<rush.val;
}
} st[MANX];
inline int lowbit(int x) {
return x&(-x);
}
inline void update(int i,int k) {
while(i<=n) {
c[i]+=k;
i+=lowbit(i);
}
}
inline int getsum(int i) {
int ret=0;
while(i>0) {
ret+=c[i];
i-=lowbit(i);
}
return ret;
}
signed main() {
ios::sync_with_stdio(false);
while(cin>>n,n) {
cin.tie(0);
ll ans=0;
memset(c,0,sizeof c);
memset(a,0,sizeof(a));
for(int i=1; i<=n; i++) {
cin>>st[i].val;
st[i].index=i;
}
sort(st+1,st+1+n);
for(int i=1; i<=n; i++)a[st[i].index]=i;
for(int i=1; i<=n; i++) {
update(a[i],1);
ans+=i-getsum(a[i]);
}
cout<<ans<<endl;
}
return 0;
}